在css的日常应用中,经常会遇到想要通过 height: 100%
来达到使子盒子与父盒子高度一样的目的,但是偶尔明明设置了height: 100%
,但是却没有达到想要的结果,这次我们就一起探索一下,什么情况height: 100%
有效,什么时候无效。
有效的情况
- 当父元素有固定高度时,子盒子可以直接使用
height: 100%
达到与父盒子高度相同的目的; 倘若父盒子是其中一个子盒子的高度撑开的时候,另外一个子盒子怎样才能通过
height: 100%
使之高度与父盒子相同呢?其实也是有办法的,在这里我们通过子绝父相的方法。请看下面的示例:
html为:<div class="wrapper"> <div class="left">我是左边</div> <div class="right">我是右边</div> </div>
css为:
position: relative; /* 触发dfc,使父元素的高度等于float的盒子 */ overflow: hidden; width: 100%; background-color: pink; } .left { float: left; height: 300px; width: 200px; background-color: red; } .right { position: absolute; left: 200px; height: 100%; background-color: blue; }
效果为
无效的情况(当父盒子被其中一个盒子的高度撑开时)
- 要设置的盒子都是inline-block时无效;
- 要设置的盒子为float元素时无效;
- 要设置的盒子为除了position的其他定位时无效;
- 要设置的盒子为flex元素时无效;