我正在使用 flexbox 在其容器中垂直对齐具有可变高度的 div(我对其他选项持开放态度)。 但是当容器小于内容时,我很难获得可靠的滚动行为。
html,
body,
.app {
height: 100%;
}
.app {
background-color: blue;
color: white;
}
.app header {
height: 80px;
background-color: red;
}
.app .container {
display: flex;
flex-direction: column;
background-color: black;
height: calc(100% - 80px);
align-items: center;
justify-content: center;
overflow: scroll;
}
.app .container .content {
width: 300px;
height: 200px;
background-color: yellow;
color: black;
}
<link rel="stylesheet prefetch" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">
<div class="app">
<header>Header</header>
<div class="container">
<div class="content">
Variable content height
</div>
</div>
</div>
非常感谢!
最佳答案
保留 overflow:auto
并且不需要使用列作为方向,只需将其保留为行即可。然后依靠 margin:auto
来保持元素居中:
没有溢出且居中的示例:
html, body, .app {
height: 100%;
}
body {
margin:0;
}
.app {
background-color: blue;
color: white;
}
.app header {
height: 80px;
background-color: red;
}
.app .container {
display: flex;
flex-direction: row;
background-color: black;
height: calc(100% - 80px);
justify-content: center;
overflow: auto;
}
.app .container .content {
width: 300px;
height:100px;
background-color: yellow;
color: black;
margin:auto;
}
<div class="app">
<header>Header</header>
<div class="container">
<div class="content">
Variable content height
</div>
</div>
</div>
溢出和滚动的例子
html, body, .app {
height: 100%;
}
body {
margin:0;
}
.app {
background-color: blue;
color: white;
}
.app header {
height: 80px;
background-color: red;
}
.app .container {
display: flex;
flex-direction: row;
background-color: black;
height: calc(100% - 80px);
justify-content: center;
overflow: auto;
}
.app .container .content {
width: 300px;
height:900px;
background-color: yellow;
color: black;
margin:auto;
}
<div class="app">
<header>Header</header>
<div class="container">
<div class="content">
Variable content height
</div>
</div>
</div>
关于html - flexbox 中最小尺寸的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48704171/