首先我们需要彻底了解overflow
属性,这个属性定义溢出元素内容区的内容会如何处理
依照我个人的理解有以下几种情况:
值 | 描述 |
---|---|
visible | 默认值,内容不会被修剪,会呈现在元素框之外 |
hidden | 内容会被修剪,并且其余内容是不可见的,目前主要用于清除浮动 |
scroll | 不管内容是否溢出,浏览器都会显示滚动条 |
auto | 内容溢出时,浏览器会显示滚动条;内容不溢出,则浏览器也不显示滚动条 |
方案一:position+overflow:auto
css
<style>
header {
height: 100px;
width: 100%;
background-color: pink;
position: absolute;
top: 0;
left: 0
}
.main {
width: 100%;
position: absolute;
top: 100px;
bottom: 100px;
left: 0;
overflow: auto;
}
footer {
height: 100px;
width: 100%;
background-color: yellow;
position: absolute;
bottom: 0;
left: 0
}
</style>
html
<body>
<div class="wrap">
<header>header</header>
<div class="main">
弹性滚动区域
</div>
<footer>footer</footer>
</div>
</body>
方案二:flex
css
<style>
html,body {
height: 100%;
}
.wrap {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
}
header,footer {
height: 100px;
width: 100%;
background-color: pink;
}
.main {
width: 100%;
flex: 1;
overflow: auto;
}
</style>
注意:这里必须要设置 html,body { height: 100% }
,否则会整体设置滚动条,而不是只有中间设置滚动条
html
<body>
<div class="wrap">
<header>header</header>
<div class="main">
弹性滚动区域
</div>
<footer>footer</footer>
</div>
</body>