css - 我如何使用flexbox使两个元素一个中心一个底部

/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:flexalign-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/

相关文章:

python - 使用 Pandas 过滤列中具有唯一值的行

c# - .NET 6 服务注册适用于具体类,但无法使用接口(interface)

python-3.x - 使用其中的值列表创建单独的字典

python - pandas 的过滤功能 - 在列中查看 NaN 值

c++ - sfinae 与非类型模板参数的概念

rust - 在这种情况下如何决定生命周期注解?

spring-boot - 使用 wicket 和 spring-boot 的浏览器拒绝样式表

html - 我可以在所有元素上使用内容可见性吗?

javascript - 条件满足后私有(private)路由不重定向

jquery - 在提交 HTML 表单后延迟 Bootstrap 模式隐藏