嵌套弹性容器时正确使用弹性属性 [英] Proper use of flex properties when nesting flex containers

查看:30
本文介绍了嵌套弹性容器时正确使用弹性属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在正确使用 flexbox 时遇到问题,想了解一下嵌套父元素和子元素的工作原理.

I am having problems using flexbox properly and wanted to get some clarification on how nesting parent and child elements works.

我知道孩子继承了父母的 flex 属性,但是对于任何进一步的后代(例如孙子"),这会恢复吗?flexbox 的正确用法是什么?

I know that the child inherits the parent's flex properties, but does that get reverted for any further descendants (e.g. 'grandchildren')? What is the proper usage of flexbox for that?

换句话说,对于 child 的 孩子,我是否也必须将 display: flex 应用于孩子?这会覆盖第一个孩子的父母的弹性属性吗?

In other words, do I have to apply display: flex to the child, too, for the child's children? Will that overwrite the first child's parent's flex properties?

.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>

推荐答案

flex 格式上下文 仅限于父/子关系.

这意味着弹性容器始终是父容器,弹性项目始终是子容器.Flex 属性仅在这种关系中起作用.

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.

flex 容器超出子级的后代不是 flex 布局的一部分,并且不会接受 flex 属性.

Descendants of a flex container beyond the children are not part of flex layout and will not accept flex properties.

您总是需要将 display: flexdisplay: inline-flex 应用于父级,以便将 flex 属性应用于子级.

You will always need to apply display: flex or display: inline-flex to a parent in order to apply flex properties to the child.

有些弹性属性只适用于弹性容器(例如,justify-contentflex-wrapflex-direction), 并且有些 flex 属性仅适用于 flex 项(例如,align-selfflex-growflex).

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).

不过,弹性项目也可以是弹性容器.在这种情况下,元素可以接受所有 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.

这篇关于嵌套弹性容器时正确使用弹性属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆