将一个弹性项目居中,将另一个弹性项目底部对齐

low*_*lly 4 html css css3 flexbox

我正在尝试使一个伸缩项目在垂直和水平方向居中。

我想将一些文本固定在flex容器的底部。

margin-top:auto在文本上只是将内部框推到顶部。有想法吗?

.container {
  background: lightblue;
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}
.container .box {
  background: goldenrod;
  height: 30px;
  width: 30px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="container">
  <div class="box"></div>
  <span>Text</span>
</div>
Run Code Online (Sandbox Code Playgroud)

这是codepen

小智 5

请尝试以下方法:

.box  {
    background:goldenrod;
    height: 30px;
    width: 30px;
    margin: auto;
  }
Run Code Online (Sandbox Code Playgroud)

  • @lowbelly,请记住,此解决方案将 `.box` 元素集中在容器的*剩余空间*中,而不是整个空间。文本占用的空间不考虑在内。因此,居中垂直偏移等于文本元素高度的长度。 (2认同)