首页 > 解决方案 > Flex align-items 不适用于 flex-wrap?

问题描述

我有时觉得 Flex 太复杂了。

演示:https ://jsfiddle.net/304xhguw/

我正在尝试创建一个末尾有多行文本的容器:

在此处输入图像描述

使用 Flex 应该很容易做到这一点,对吧?

div {
  display: flex;
  align-items: flex-end;
  padding: 20px;
  height: 300px;
  background: #222;
  flex-wrap: wrap;
}

h1 {
  width: 100%;
}

h1, p {
  color: #fff;
}

完成后,容器使用 flex,在末尾对齐项目,并且 h1 由于wrapwidthof创建了一个新行100%。完美的。

并不真地:

在此处输入图像描述

等等,这里刚刚发生了什么?<p>与底部对齐,但是<h1>- 不是?但是父容器有align-items: flex-end;,这是什么魔法?

不用担心,有一些惊人的属性应该可以工作,让我们试试:

h1 { align-self: flex-end; }

什么都没有改变,嗯,好吧,那么也许:

h1 { align-self: end; }

好吧,现在是什么鬼?

拜托,谁能向我解释这里到底发生了什么,为什么 Flex 如此愚蠢不直观?我本可以在 20 秒内使用旧的position: relative甚至(我知道,我知道...)来完成此操作。tables只有我还是 Flexbox 感觉像是一个非常强大的工具,对于大约 95% 的最简单的情况来说,它是一种过度杀伤和令人头疼的工具?

注意:我不想添加任何额外的 DIVS 包装或容器。我觉得将 h1 和 p 包装在一个 div 中然后对齐会相当容易,但我不会在 2021 年使用 Flex 来添加不必要的标记。

标签: cssflexbox

解决方案


编辑1:

我忘了在关于 flex-wrap 的原始答案中提到,当它的启用和行项目被包装并创建多行 flexbox 时。在这种情况下,当您对齐内容时(我没有提到项目,因为您想考虑所有元素而不仅仅是单行上的元素),您需要使用align-content: flex-end.

这将在 flexbox 的末尾打包 flex 布局中出现的所有多行,并且您的项目将在底部对齐。

当您使用align-items: flex-end时,flexbox 会根据放置元素的行对齐项目。

当您使用 时align-items: flex-end,元素会根据它们的线对齐。

Heading
--------- // line 1
Paragraph
--------- // line 2

当你使用 时align-content: flex-end,线条会在底部移动。

Heading
Paragraph
--------- // multi lines are packed at the end of the flexbox

这是适合您的工作示例:

body { margin: 0; padding: 0; }

div {
  display: flex;
  align-content: flex-end;
  padding: 20px;
  height: 300px;
  background: #222;
  flex-wrap: wrap;
}

h1 {
  width: 100%;
}

h1, p {
  color: #fff;
}
<div>
  <h1>Header something something something header more of header and more and more</h1>
  <p>Just some content at the end of the div not sure what more to write</p>
</div>

https://jsfiddle.net/h9ykz0ue/


您的代码实际上没有任何问题。我建议您使用align-items: flex-end;而不是align-items: end;在您的 flex 容器中。

您在这里面临的问题是保证金。两者<h1>都有<p>自己的利润。

由于 flex 布局,这些元素是并排呈现的(但在视觉上它们是垂直堆叠的,这要归功于flex-wrap)。边距折叠也不会出现在您的布局中,因为它在 flex 布局中不受支持,它只出现在块布局中。

我建议您不要使用flex-wrap: wrap,flex-direction: columnjustify-content: flex-end这种方式使用:

div {
  .
  .
  flex-direction: column;
  justify-content: flex-end;
  .
  .
}

这是我所说的快速演示:

body {
  margin: 0;
  padding: 0;
}

div {
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  padding: 20px;
  height: 300px;
  background: #222;
}

h1 {
  width: 100%;
}

h1, p {
  color: #fff;
}

p {
  margin: 0;
}
<div>
  <h1>Header something something something header more of header and more and more</h1>
  <p>Just some content at the end of the div not sure what more to write</p>
</div>

在这里,我还删除了边距,<p>以便<h1>更接近它。如果不需要,您可以删除样式。


推荐阅读