需求:有一个高度自适应的div,里面有两个div,一个高度100px,希望另一个填满剩下的高度
1.用flex 来实现
思路:flex 垂直布局(column),第一个元素固定高度,第二个元素flex-shrink 设为1,自动放大填充父容器。
<div class="parent"> <div class="child">this is a</div> <div class="child">this is b</div> </div>
html,body{ height: 100%; width:100%; margin: 0; padding: 0; } .parent{ display: flex; flex-direction: column; height: 100%; } .child{ border: 1px solid; } .child:nth-child(1){ height: 100px; } .child:nth-child(2){ flex:1; }
2.设置容器和绝对定位来实现
思路:容器padding-top 100px,并且设置border-box,第一个元素绝对定位 100px,第二个元素100%
a.容器留出100px位置,
b.元素绝对定位,放到容器预留的位置上
<div class="parent"> <div class="child">this is a</div> <div class="child">this is b</div> </div>
html,body{ height: 100%; width:100%; margin: 0; padding: 0; } .parent{ height: 100%; box-sizing: border-box;/* 重要 */ padding-top:100px;/* 重要 */ } .child:nth-child(1){ height: 100px; width: 100%; position: absolute;/* 重要 */ top: 0; left: 0; background: #c569b1; } .child:nth-child(2){ height: 100%; background: #9ecc44; }
3.设置容器和偏移来实现:
和第2种思路一样,用偏移来实现
<div class="parent"> <div class="child">this is a</div> <div class="child">this is b</div> </div>
html,body{ height: 100%; width:100%; margin: 0; padding: 0; } .parent{ height: 100%; box-sizing: border-box;/* 重要 */ padding-top:100px;/* 重要 */ } .child:nth-child(1){ height: 100px; width: 100%; margin-top: -100px; background: #c569b1; } .child:nth-child(2){ height: 100%; background: #9ecc44; }