html - 两列 flex 布局,内容向中间对齐

标签 html css flexbox

使用这段代码:

.row {
  display: flex;
  text-align: center;
}

.col {
  flex: 1;
}
<div class='row'>
  <div class='col'>
    <h1>Left</h1>
    <h2>Some longer text</h2>
  </div>
  <div class='col'>
    <h1>Right</h1>
    <h2>Some longer text</h2>
  </div>
</div>

我得到这样的输出

------------------------------------------------------------------
|            Left               |             Right              |
|       Some longer text        |       Some longer text         |
------------------------------------------------------------------

(虚线表示容器)。

我想要的是让每一列中的元素相对于彼此保持居中,但偏向于列分隔符,并带有一些填充,例如

------------------------------------------------------------------
|                 Left        |       Right                      |
|           Some longer text  |  Some longer text                |
------------------------------------------------------------------

我怎样才能做到这一点?

最佳答案

请查收附件fiddle

您可以使用 align-items: center 进行垂直居中对齐或然后进行水平对齐,在特定元素上使用 align-self 以 flex-start、flex-end 或 center。

只需在此处添加 css 代码。

.row {
  display: flex;
  margin: 0 -15px;
}

.col {
    flex: 1;
    flex-flow: column wrap;
    align-items: center;
    display: flex;
    padding: 0 15px;
}
.col:first-child h1,
.col:first-child h2{
align-self: flex-end;
}
.col:last-child h1,
.col:last-child h2{
align-self: flex-start;
}

关于html - 两列 flex 布局,内容向中间对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58090471/

相关文章:

html - 在 flexbox 中将文本居中放置在图像上

html - float 不按预期工作

html - 使用 CSS 将来自一个 TR 的两个 TD 堆叠在一起

css - 如何为下面的图像框(不是阴影框)做 CSS

html - 如何在 Angularjs 中获得 0 值长度?

html - 如何根据标签文本长度拉伸(stretch)容器宽度?

CSS flex 盒 : How to fill the remaining screen height with a nested div?

html - 在不使用 <br/> 的情况下换行

javascript - 可拖动元素

javascript - 重置 HTML 正文后 Bootstrap 模式不会关闭