嵌套弹性容器时正确使用弹性属性

flexweb developmentfront end scriptsjavascript

弹性容器始终是父级,弹性项目始终是子级。弹性格式化上下文的范围仅限于父/子关系。

子级以外的弹性容器的后代不属于弹性布局,不会接受弹性属性。某些弹性属性仅适用于弹性容器 -

  • justify-content、
  • flex-wrap 和
  • flex-direction

某些弹性属性仅适用于弹性项目"

  • align-self
  • flex-grow
  • flex

始终将 display: flex 或 display: inline-flex 应用于父级,以便将弹性属性应用于子级。

现在让我们看一个例子。我们的父级 div parentBox 中有两个 div -

<div class='parentBox'>
   <div class='childBox'>
      <div class='babyChildBox'>Parent's Child</div>
      <div class='babyChildBox'>Parent's Child</div>
   </div>
      <! - - -

      !-->
</div>

父容器的样式。我们使用 CSS Flex 简写属性 −

.parentBox {
   display: flex;
   flex: 1 0 100%;
   background-color:yellow;
   border: 3px solid skyblue;
}

对于 Child,即 childBox,我们再次使用简写属性来设置灵活项目的灵活长度 -

.childBox {
   flex: 1 1 50%
   background-color: green;
   color: white;
   border: 1px solid blue;
}

上面 .childBox 中嵌套的子元素设置了 Flex。此元素和上面元素嵌套了 flex 容器 −

.babyChildBox {
   flex: 1 1 50%;
   background-color: orange;
}

示例

现在让我们看一下正确嵌套弹性容器的完整示例 -

<!DOCTYPE html>
<html>
<head>
   <style> 
      .parentBox {
         display: flex;
         flex: 1 0 100%;
         background-color:yellow;
         border: 3px solid skyblue;
      }
      .childBox {
         flex: 1 1 50%
         background-color: green;
         color: white;
         border: 1px solid blue;
      }
      .babyChildBox {
         flex: 1 1 50%;
         background-color: orange;
      }
   </style>
</head>
<body>
   <h1>Implementing Flex</h1>
   <div class='parentBox'>
      <div class='childBox'>
         <div class='babyChildBox'>Parent's Child</div>
         <div class='babyChildBox'>Parent's Child</div>
      </div>
      <div class='childBox'>
         <div class='babyChildBox'>Parent's Child</div>
         <div class='babyChildBox'>Parent's Child</div>
      </div>
   </div>
</body>
</html>

输出


相关文章