将一个flex项目居中对齐,同时将另一个项目底部对齐。

4

我想要将一个flex项目垂直和水平居中。

我想让一些文本固定在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;
}
<div class="container">
  <div class="box"></div>
  <span>Text</span>
</div>

这是codepen链接。


尝试使用其他浏览器了吗?这里居中得很好。 - Xorifelse
3个回答

8
尝试使用以下方法:

.box  {
    background:goldenrod;
    height: 30px;
    width: 30px;
    margin: auto;
  }


那个是赢家,谢谢! - lowbelly
2
@lowbelly,请记住,此解决方案将.box元素置于容器的剩余空间中心,而不是整个空间中心。文本占用的空间未被考虑在内。因此,垂直居中会偏移一个等于文本元素高度的长度。 - Michael Benjamin

3
由于flexbox对容器中自由空间的分配涉及,因此在这种情况下,margin-top: auto将无法起作用,因为另一侧没有平衡点。
因此,一种将框居中并使文本底部对齐的方法是创建文本元素的副本并将其放置在框的相反侧。这将创建一个平衡点。
两端平衡后,flex对齐属性(包括auto边距)可以起作用。
在这种情况下,即使使用justify-content: space-between也可以。
当然,您需要将visibility: hidden应用于副本元素。

.container {
  background: lightblue;
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}
.box {
  background: goldenrod;
  height: 30px;
  width: 30px;
  margin: auto 0;   /* or instead use justify-content: space-between on .container */
}
span:first-child {
  visibility: hidden;
}
<div class="container">
  <span>Text</span>
  <div class="box"></div>
  <span>Text</span>
</div>

或者,可以使用伪元素代替副本元素。

一种更少干扰且更符合语义的方法是使用伪元素作为副本。但是,为了使此方法工作,您需要知道实际元素的高度,因为您需要精确匹配它。

类似以下代码将创建平衡:

.container::before {
    content: "";
    height: 15px; /* must match actual element's height */
}

.container {
  background: lightblue;
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: space-between;
  flex-direction: column;
  align-items: center;
  padding: 10px;
}
.box {
  background: goldenrod;
  height: 30px;
  width: 30px;
}
span {
  height: 15px;
}
.container::before {
  content: "";
  height: 15px;
}
<div class="container">
  <div class="box"></div>
  <span>Text</span>
</div>


复制文本是一种粗暴的黑客行为,会对SEO和可访问性产生影响。 - coreyward
1
@coreyward,黑客并不是理想的解决方案,但它们通常很有用。使用表格/浮动进行布局,使用UL/OL进行导航,在flex容器中使用重复元素/伪元素实现平衡。这只是一个想法,用户可以选择实施或忽略。 - Michael Benjamin

2

以下是一种实现方法。

在你的.container CSS规则中添加position: relative,然后使用绝对定位在.box上定位span到父容器底部。

你可以通过允许.box具有100%的宽度,然后使用text-align: center来居中文本。

.container {
  background: lightblue;
  width: 300px;
  height: 300px;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  padding: 10px;
  position: relative;
}
.box {
  background: goldenrod;
  height: 30px;
  width: 30px;
}
span {
  position: absolute;
  left: 0;
  bottom: 0;
  width: 100%;
  text-align: center;
}
<div class="container">
  <div class="box"></div>
  <span>Text</span>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接