Flex align-items在使用flex-wrap时无法工作吗?

15 浏览
0 Comments

Flex align-items在使用flex-wrap时无法工作吗?

有时我觉得Flex太过复杂了。

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

我试图创建一个容器,在其末尾有多行文本:

enter image description here

使用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由于wrapwidth100%而换行。完美。

但事实并非如此:

enter image description here

等等,这里到底发生了什么?被对齐到底部,但是

却没有?但是父容器有align-items: flex-end;,这是什么魔法?

别担心,有一些很棒的属性应该可以解决,让我们试试:

h1 { align-self: flex-end; }

没有任何变化,嗯,好吧,那也许是这样:

h1 { align-self: end; }

好了,这次到底怎么了?

请问有人可以解释一下到底发生了什么,为什么Flex如此难以理解?我本可以在20秒内使用老旧的position: relative或者甚至tables(我知道,我知道...)来实现这个效果。是只有我觉得Flexbox像是一个强大得过头而且令人头疼的工具,对于95%的最简单的情况来说都太过复杂吗?

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

0
0 Comments

Flex align-items does not work with flex-wrap的问题是指在使用flex-wrap属性时,align-items属性无法正常工作的情况。出现这个问题的原因是,当设置了flex-wrap: wrap时,元素会被分行显示,但是align-items属性只能在单行中起作用,无法在多行中对齐元素。

解决这个问题的方法是,可以使用flex-direction: column来代替flex-wrap属性。通过将flex-direction设置为column,元素会按照列的方式排列,而不是按照行。然后可以使用justify-content: flex-end来在列的末尾对齐元素。同时,需要注意设置合适的高度(height)和填充(padding)值来控制元素的显示效果。

以下是使用flex和flex-direction解决这个问题的代码示例:

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

通过以上的代码设置,可以在使用flex-wrap属性时,使align-items属性正常工作。

0
0 Comments

flex-wrap enabled时,当行项目被换行并创建多行flexbox时,如果要对内容进行对齐,需要使用align-content: flex-end。这将把出现在flex布局中的多行都放在flexbox的末尾,并使得项目底部对齐。

而使用align-items: flex-end时,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;
}

Header something something something header more of header and more and more

Just some content at the end of the div not sure what more to write

另外,如果不想使用flex-wrap: wrap,可以使用flex-direction: column和justify-content: flex-end来实现相同的效果。这是另一种解决方法的示例代码:

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;
}

Header something something something header more of header and more and more

Just some content at the end of the div not sure what more to write

0