CSS width与继承的关系

1 起因

在做页面时,想把搜索按钮放在页面底部(在正常流中,搜索按钮紧挨着上部分),即图一变为图二。
在这里插入图片描述

图一
在这里插入图片描述

图二

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

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值