html结构如下:
<html>
<body>
<div class="content">
<div class="top"></div>
<div class="bottom"></div>
</div>
</body>
</html>
1.border-box + 负margin方法
实现原理:设置父元素为IE盒模型,且其padding-top为100px, 非绝对定位的子元素“bottom"高度为100%;子元素"top"的margin-top为-100px,导致其会整体上移100px, 也就正好遮挡了父元素的padding-top部分了。
注意点:父元素记得设置box-sizing:border-box
<style>
html,body{
height: 100%;
padding: 0;
margin: 0;
}
.content{
height: 100%;
padding: 100px 0 0;
box-sizing: border-box;
}
.top{
height: 100px;
margin: -100px 0 0;
background: greenyellow;
}
.bottom{
height: 100%;
background: pink;
}
</style>
2.border-box + 绝对定位方法
实现原理:由于父元素被设置成了IE盒模型,且父元素的padding-top与子元素“top”的高度是一样的, 因此绝对定位的子元素“top”属性设为top:0时,其自然而然就处于父元素的padding-top区域了。(高度相等正好遮盖padding-top,而非绝对定位的子元素bottom的高度设为100%时, 其高度就是父元素盒模型中的content里的高度(不包含padding及margin值),因此正好也就填充了 剩余空间了。
注意点:父元素记得设置position:relative
及box-sizing:border-box
<style>
html,body{
height: 100%;
padding: 0;
margin: 0;
}
.content{
position: relative;
height: 100%;
padding: 100px 0 0;
box-sizing: border-box;
}
.top{
position: absolute;
height: 100px;
width: 100%;
top: 0;
left: 0;
background: greenyellow;
}
.bottom{
height: 100%;
background: pink;
}
</style>
3.flex方法
实现原理:该方法主要部分就是使用了flex:1属性来实现’子元素’bottom"的自动伸缩
注意点:注意兼容性
<style>
html,body{
height: 100%;
padding: 0;
margin: 0;
}
.content{
height: 100%;
display: flex;
flex-direction: column;
}
.top{
height: 100px;
background: greenyellow;
}
.bottom{
flex: 1;
background: pink;
}
</style>
4.绝对定位方法
实现原理:”bottom“元素采用absolute 绝对定位后,再使用bottom:0属性,会使得其紧贴其包裹的元素的底部。 (准确说是其含有position:relative的父级或以上的包裹元素 )
注意点:父级元素别忘记使用position:relative,否则将定位至html上
<style>
html,body{
height: 100%;
padding: 0;
margin: 0;
}
.content{
height: 100%;
position: relative;
}
.top{
height: 100px;
background: greenyellow;
}
.bottom{
position: absolute;
top: 100px;
left: 0;
right: 0;
bottom: 0;
background: pink;
}
</style>