嵌套 flex 容器时正确使用 flex 属性 [英] Proper use of flex properties when nesting flex containers
问题描述
我在正确使用 flexbox 时遇到问题,想了解一下嵌套父元素和子元素的工作原理.
我知道孩子继承了父母的 flex.但是,如果您需要为其孩子(婴儿)弯曲孩子,这是否会被覆盖?flexbox 的正确用法是什么?
为了其孩子(婴儿)的缘故,我什么时候必须将 display: flex
应用到孩子,否则会覆盖孩子的父母 flex?
.parent-container {显示:弹性;弹性:1 0 100%;背景颜色:黄色;}.子容器{弹性:1 1 50%背景颜色:蓝色;}.baby-of-child-container {弹性:1 1 50%;背景颜色:绿色;}
<div class='child-container'><div class='baby-of-child-container'>child</div><div class='baby-of-child-container'>child</div><div class='child-container'><div class='baby-of-child-container'>child</div><div class='baby-of-child-container'>child</div>
flex 格式上下文 仅限于父/子关系.
这意味着弹性容器总是父项,而弹性项总是子项.Flex 属性仅在这种关系中起作用.
超出孩子的 flex 容器的后代不是 flex 布局的一部分,不会接受 flex 属性.
您总是需要将 display: flex
或 display: inline-flex
应用于父级,以便将 flex 属性应用于子级.
某些 flex 属性仅适用于 flex 容器(例如,justify-content
、flex-wrap
和 flex-direction
),并且有某些 flex 属性仅适用于 flex 项(例如,align-self
、flex-grow
和 flex
).>
然而,弹性项目也可以是弹性容器.在这种情况下,元素可以接受所有 flex 属性.由于每个属性执行不同的功能,因此不存在内部冲突,无需覆盖任何内容.
I am having problems using flexbox properly and wanted to get some clarification on how nesting parent and child elements works.
I know that the child inherits the parent's flex. But does that get overwritten if you need to flex a child for its children (baby)? What is the proper usage of flexbox?
When do I have to apply display: flex
to the child for its child's (baby's) sake, or will that overwrite the child's parent flex?
.parent-container {
display: flex;
flex: 1 0 100%;
background-color:yellow;
}
.child-container {
flex: 1 1 50%
background-color: blue;
}
.baby-of-child-container {
flex: 1 1 50%;
background-color: green;
}
<div class='parent-container'>
<div class='child-container'>
<div class='baby-of-child-container'>child</div>
<div class='baby-of-child-container'>child</div>
</div>
<div class='child-container'>
<div class='baby-of-child-container'>child</div>
<div class='baby-of-child-container'>child</div>
</div>
</div>
The scope of a flex formatting context is limited to a parent/child relationship.
This means that a flex container is always the parent and a flex item is always the child. Flex properties work only within this relationship.
Descendants of a flex container beyond the children are not part of flex layout and will not accept flex properties.
You will always need to apply display: flex
or display: inline-flex
to a parent in order to apply flex properties to the child.
There are certain flex properties that apply only to flex containers (e.g., justify-content
, flex-wrap
and flex-direction
), and there are certain flex properties that apply only to flex items (e.g., align-self
, flex-grow
and flex
).
However, flex items can also be flex containers. In such cases the element can accept all flex properties. Being that each property performs a different function, there is no internal conflict and nothing needs to be overridden.
这篇关于嵌套 flex 容器时正确使用 flex 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!