width:100%和width:inherit

前几天遇到过这么一个问题。我想让子盒子的宽度等于父盒子的宽度。父盒子宽度为一个具体值比如说200px.我将子盒子宽度设为了100%。按道理说应该是可以等于父盒子的宽度的,但结果并没有,而是通栏了。然后我又将子盒子宽度设为了inherit。结果宽度就是父盒子的宽度了。

HTML结构如下:

    <body>
        <div class="parent">
            <div class="child">
                hello world
            </div>
        </div>
    </body>

我想了很久没有想出来,后来请同事帮我一看。原来我的子盒子设了绝对定位,但父盒子没有设置相对定位。所以子盒子脱离了父盒子,导致子盒子的百分之百直接和body的宽度一致了。而子盒子虽然定位上脱离了文档流,但在节点树上他依然是父盒子的儿子,所以如果设置width:inherit的时候,浏览器会将父盒子的宽度赋值给他。

那么解决的办法有两种,一种是像我这样设置成width:inherit。这样的好处是节约代码,但有一点点小小的兼容问题。ie8以下的浏览器不支持inherit属性值。如果你们公司放弃IE8以下的兼容,那我觉得用inherit是很好的一种方式。

.parent{
    width: 300px;
    height: 300px;
    background: deeppink;        
}
.child{
    width: inherit;
    position: absolute;
    background: pink;
}

第二种就是在父盒子上加上相对定位,这种方法的好处是兼容性比较好,缺点就是代码量稍微多了两句,而且要细心一些不能像我一样忘记加相对定位

.parent{
          width: 300px;
          height: 300px;
          background: deeppink;
          position: relative;            
    }
.child{
          width: 100%;
          position: absolute;
          background: pink;
    }
原文地址:https://www.cnblogs.com/ada-blog/p/7257406.html