我有一个嵌套在列向 flex 盒中的行向 flex 盒,但是当我想在子项中使用 align-content
时,它不起作用。
当我用 display:block
替换父级的 display:flex
时,它起作用了。
在下面的代码中,我们可以看到 .row
align-content: flex-end;
不起作用。但是,如果我将 .column
display: flex;
替换为 display: block;
,则 align-content: flex-end;
有效。
请问可以解决这个问题吗?
body {
background-color: grey;
}
.column {
display: flex;
flex-flow: column nowrap;
justify-content: flex-start;
align-items: stretch;
background-color: green;
}
.row {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
align-content: flex-end;
align-items: center;
background-color: red;
}
.row-test {
min-height: 200px;
}
span {
width: 30%;
background-color: orange;
}
<body class="column">
<section class="row row-test">
<span>Test Test Test Test Test Test Test Test Test</span>
<span>Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test Test</span>
</section>
</body>
最佳答案
当主 flex 容器切换到 display: block
时 align-content
“起作用”的事实只是一个浏览器错误。
它根据需要将 flex 元素移动到底部,但仅在 Firefox 中。
在 Chrome 中它什么都不做,这是正确的行为(根据规范)。
在 IE11 中,它会将元素移到顶部(也是不一致的)。
这些错误和不一致不应作为指导依据,因为它们无助于解释 align-content
属性的工作原理。
在单行 flex 容器中,就像问题中的容器一样,align-content
没有效果。要使用的属性是 align-items
。
在多行 flex 容器中,要使用的属性是align-content
。
此外,align-self
属性与align-items
密切相关。一个旨在覆盖另一个。它们一起发挥作用。
来自规范:
8.3. Cross-axis Alignment: the
align-items
andalign-self
properties
align-items
sets the default alignment for all of the flex container’s items, including anonymous flex items.align-self
allows this default alignment to be overridden for individual flex items.8.4. Packing Flex Lines: the
align-content
propertyThe
align-content
property aligns a flex container’s lines within the flex container when there is extra space in the cross-axis, similar to howjustify-content
aligns individual items within the main-axis. Note, this property has no effect on a single-line flex container.
就这个问题而言,忘记align-content
。这是没用的(除非你的 flex 元素换行)。
只需使用align-items: flex-end
(或span
上的align-self: flex-end
):
body {
background-color: grey;
}
.column {
display: flex;
flex-flow: column nowrap;
justify-content: flex-start;
align-items: stretch;
background-color: green;
}
.row {
display: flex;
flex-flow: row wrap;
justify-content: space-around;
align-content: flex-end; /* will work when items have wrapped */
align-items: flex-end; /* adjusted; works when items in one line */
background-color: red;
}
.row-test {
min-height: 200px;
}
span {
width: 30%;
background-color: orange;
/* align-self: flex-end; this would also work on single line container */
}
<body class="column">
<section class="row row-test">
<span>Test Test Test Test Test Test Test Test Test</span>
<span>Test Test Test Test Test Test Test Test Test Test Test
Test Test Test Test Test Test Test Test Test Test Test</span>
</section>
</body>
关于html - 对齐内容不适用于 flex 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37226787/