学习记录305@CSS中height的继承问题

width属性是可以继承的,也就是说,当子元素不指定宽度,会自动继承上级元素的宽度。
但是height是不能继承上级元素的,如下例子:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
.father{
    
    
    width:1000px;
    height:100px;
    margin:0 auto;
    background-color:red;
}

.son{
    
    
    
    width:1000px;
    margin:0 auto;
    background-color:yellow;
}
</style>
</head>
<body>
<div class="father">
     <div class="son"></div>
</div>
</body>
</html>

在这里插入图片描述
子元素的高度为零,并没有继承上级元素的高度。

那如果是将子元素高度设置为100%呢,自然就是继承上级元素的高度了:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>
.father{
    
    
    width:1000px;
    height:100px;
    margin:0 auto;
    background-color:red;
}

.son{
    
    
    height:100%;
    width:1000px;
    margin:0 auto;
    background-color:yellow;
}
</style>

</head>
<body>
   <div class="father">
       <div class="son"></div>
   </div>
</body>
</html>

在这里插入图片描述
但是如果有个爷爷元素有高度,父亲元素没有高度,那么孙子元素设置100%则也不会继承爷爷元素高度,也就是说,设置100%高度只能继承父级元素的高度而不能继承爷爷元素的高度:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
<style>

.grandfather{
    
    
    width:1000px;
    height:100px;
    margin:0 auto;
    background-color:red;
}
.father{
    
    
    width:1000px;
    margin:0 auto;
    background-color:red;
}

.son{
    
    
    height:100%;
    width:1000px;
    margin:0 auto;
    background-color:yellow;
}
</style>

</head>
<body>
<div class="grandfather">
    <div class="father">
        <div class="son"></div>
    </div>
</div>
</body>
</html>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44663675/article/details/108355164
今日推荐