/image/e2n5o.png
我想通过 flexbox 实现这样的布局。 body
是 flex 容器,只有两个 flex 元素,一张卡片和一个页脚。这是一个 simplified codepen link .我怎样才能在页面底部制作页脚,而卡片现在居中。
body {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
.container {
width: 400px;
height: 300px;
background-color: green;
}
.footer {
margin-bottom: 20px;
background-color: yellow;
width: 200px;
height: 50px;
}
<div class="container"></div>
<div class="footer"></div>
如果我添加 margin-top:auto
,页脚的位置会正确,但容器会移到顶部。
如果我在 body
中添加 gap
,容器将不会位于中心
最佳答案
为绿卡使用另一个元素,并使用 flex-grow: 1
使 .container
填充所有可用空间。
在 .container
上使用 display:flex
和 align-items:center
使卡片垂直居中。
body{
display:flex;
flex-direction:column;
align-items:center;
height:100vh;
}
.container{
flex-grow: 1;
display: flex;
align-items: center;
}
.card {
width:400px;
height:300px;
background-color:green;
}
.footer{
margin-bottom:20px;
background-color:yellow;
width: 200px;
height:50px;
}
<div class="container">
<div class="card"></div>
</div>
<div class="footer"></div>
正文不需要 justify-content:center;
所以你也应该删除它。
另一种方法,如果您希望 .container
具有 100%
宽度。
body {
display: flex;
flex-wrap: wrap;
height: 100vh;
}
.container {
width: 100%; /* NEW */
flex-grow: 1;
display: flex;
align-items: center;
justify-content: center; /* NEW */
}
.card {
width: 400px;
height: 300px;
background-color: green;
}
.footer {
margin-bottom: 20px;
background-color: yellow;
width: 200px;
height: 50px;
margin: auto; /* NEW */
}
<div class="container">
<div class="card"></div>
</div>
<div class="footer"></div>
https://stackoverflow.com/questions/70414515/