flexbox调整内容导致溢出:自动无法正常工作



我有一个容器div,它的内容可以垂直增长。我使用overflow-y: auto作为容器,以使我的页面看起来不错。但是,当内容的高度小于容器的高度时,我需要将所有内容都放在中心。所以我用flexbox来做这个。但问题是,我无法完全滚动查看内容的顶部。


以下是有问题代码的一个简单示例:

<html lang="en">
<head>
<style>
.container {
width: 20rem;
height: 20rem;
background-color: red;
display: flex;
justify-content: center;
flex-direction: column;
align-items: center;
overflow-y: auto;
}
.child {
width: 10rem;
height: 40rem;
background-color: blue;
flex-shrink: 0;
}
.top {
width: 1rem;
height: 1rem;
background-color: green;
}
</style>
</head>
<body>
<div class="container">
<div class="child">
<div class="top"></div>
</div>
</div>
</body>
</html>

这个问题的解决方案之一是使用flex容器中元素的相反顺序,即在您的情况下,使用flex-direction: column-reverse而不是flex-direction: column

下面的示例#1:

.container {
width: 20rem;
height: 20rem;
background-color: red;
display: flex;
justify-content: center;
flex-direction: column-reverse;
align-items: center;
overflow-y: auto;
}
.child {
width: 10rem;
min-height: 0;
height: 40rem;
background-color: blue;
flex-shrink: 0;
max-height: 150%;
}
.top {
width: 1rem;
height: 1rem;
background-color: green;
}
<div class="container">
<div class="child">
<div class="top">test</div>
</div>
</div>

第二种解决方案是考虑使用进行中心对齐,也可以使用justify-content: space-between和伪元素::after::before

下面的示例#2:

.container {
width: 20rem;
height: 20rem;
background-color: red;
display: flex;
justify-content: space-between;
flex-direction: column;
align-items: center;
overflow-y: auto;
}
.container::before,
.container::after {
content: '';
}
.child {
width: 10rem;
min-height: 0;
height: 40rem;
background-color: blue;
flex-shrink: 0;
max-height: 150%;
}
.top {
width: 1rem;
height: 1rem;
background-color: green;
}
<div class="container">
<div class="child">
<div class="top">test222</div>
</div>
</div>

最新更新