本文最后更新于:2024年11月13日 下午
                
              
            
            
              前言
CSS3 div继承父元素宽度
父子元素的宽度
1.正常情况
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 
 | <style>.parent{
 width: 200px;
 height: 300px;
 background-color: aquamarine;
 }
 .child{
 width: 100%;
 background-color: red;
 }
 </style>
 
 <div class="parent">
 <div class="child">
 hello world
 </div>
 </div>
 
 
 | 

此时,子元素宽度等于父元素宽度,正是我们要的效果。
2.有定位的情况
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | <style>.parent{
 width: 200px;
 height: 300px;
 background-color: aquamarine;
 position:relative;
 }
 .child{
 width: 100%;
 background-color: red;
 position:absolute;
 }
 </style>
 
 <div class="parent">
 <div class="child">
 hello world
 </div>
 </div>
 
 
 | 
此时,子元素宽度也是正常的,等于父元素宽度。
3.父元素无定位,子元素是绝对定位
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | <style>.parent{
 width: 200px;
 height: 300px;
 background-color: aquamarine;
 }
 .child{
 width: 100%;
 background-color: red;
 position:absolute;
 }
 </style>
 
 <div class="parent">
 <div class="child">
 hello world
 </div>
 </div>
 
 
 | 
此时,子元素的宽度发生了变化,宽度等于body的宽度了。这是因为子元素设置了绝对定位,它脱离了父元素文档流,所以宽度直接和body一样了。

解决方法:
1.给父元素加上相对定位;
2.将子元素的width:100%;改成width:inherit;,表示继承父元素的宽度。注意:IE8不支持inherit属性
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 
 | <style>.parent{
 width: 200px;
 height: 300px;
 background-color: aquamarine;
 }
 .child{
 width: inherit;
 background-color: red;
 position:absolute;
 }
 </style>
 
 <div class="parent">
 <div class="child">
 hello world
 </div>
 </div>
 
 
 |