1 起因
在做页面时,想把搜索按钮放在页面底部(在正常流中,搜索按钮紧挨着上部分),即图一变为图二。
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/9f2b615f0944bc3f5cece925c180e818.png)
2 现象
在给元素设置position:absolute;
样式后,发现搜索框变小了;如图3;
3 思考
在给元素设置定位position:absolute
后,元素脱离正常流,不再继承父元素宽度。
4 验证
4.1 正常流中,块级子元素width继承父元素属性
写如下代码:
<div class="father">
<div class="child">333</div>
</div>
<style>
.father{
background-color: blue;
width: 100%;
height: 500px;
}
.child{
height: 200px;
background-color: yellow;
}
</style>
浏览器显示:
由以上我们可以看出,块级子元素可以继承父元素宽度。
4.2 行内元素不继承父元素宽度
我们把child的设为行内
<div class="father">
<div class="child">333</div>
</div>
<style>
.father{
background-color: blue;
width: 100%;
height: 500px;
}
.child{
height: 200px;
background-color: yellow;
display: inline;
width: 500px;
}
</style>
结果如下:
其实行内元素设置宽度无效
4.3 行内块子元素不继承父元素width属性
把子元素设置为inline-block;
<div class="father">
<div class="child">333</div>
</div>
<style>
.father{
background-color: blue;
width: 100%;
height: 500px;
}
.child{
// height: 200px;
background-color: yellow;
display: inline-block;
// width: 500px;
}
</style>
4.4 浮动子元素不继承父元素宽度
代码:把子元素设置为浮动;
<div class="father">
<div class="child">333</div>
</div>
<style>
.father{
background-color: blue;
width: 100%;
height: 500px;
}
.child{
height: 200px;
background-color: yellow;
float: left;
}
</style>
结果:
注意:浮动元素会脱离正常文档流
4.5 定位absolute的子元素不继承父元素的宽度属性
代码:
<div class="father">
<div class="child">333</div>
</div>
<style>
.father{
background-color: blue;
width: 100%;
height: 500px;
}
.child{
height: 200px;
background-color: yellow;
position: absolute;
}
</style>
结果:
如果把position的值改为relative,可以发现是继承的。
注意:absolute的元素脱离文档流,而position的元素实际还在文档流中,fixed效果和absolutey一样脱离文档正常流。
5 扩展
width的值可以设为百分比,如果不能继承父元素宽度属性,那么百分比的参考值是谁呢?
参考:
《css权威指南》第三版
https://www.cnblogs.com/gaogch/p/10652694.html