Correctly use elastic properties to nest elastic containers
P粉369196603
2023-08-24 11:43:49
<p>I'm having some issues using flexbox correctly and would like some clarification on the nesting of parent and child elements. </p>
<p>I know that child elements inherit the flex property of the parent element, but what happens to further descendant elements (e.g. "grandchildren")? What is the correct usage of flexbox in this case? </p>
<p>In other words, do I need to apply <code>display: flex</code> to child elements as well, to apply to child elements of child elements? Will this override the flex property of the first child element's parent element? </p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">.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;
}</pre>
<pre class="brush:html;toolbar:false;"><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></pre>
<p><br /></p>
The scope of a flex formatting context is limited to parent-child relationships.
This means that the flex container is always the parent, and the flex items are always the children. Flex properties only work within this relationship.
Descendants of a flex container that exceeds the child level do not belong to the flex layout and will not accept flex attributes.
In order to apply flex properties to children, you always need to apply
display: flex
ordisplay: inline-flex
to the parent.Some flex properties only apply to flex containers (such as
justify-content
,flex-wrap
, andflex-direction
), while some flex properties Applies only to flex items (such asalign-self
,flex-grow
, andflex
).However, flex items can also be flex containers. In this case, the element can accept all flex properties. Since each property performs a different function, there are no internal conflicts and nothing needs to be overridden.