巢狀彈性容器時彈性屬性的正確使用
彈性容器始終是父容器,彈性項始終是子級。彈性格式化上下文的範圍僅限於父級/子級關係。
彈性容器的後代(除了子代之外)不屬於彈性佈局,不會接受彈性屬性。有某些彈性屬性僅適用於彈性容器 −
- 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 彈性速寫屬性 −
.parentBox {
display: flex;
flex: 1 0 100%;
background-color:yellow;
border: 3px solid skyblue;
}
對於子級(即 childBox),我們再次使用速寫屬性在彈性項上設定彈性長度 −
.childBox {
flex: 1 1 50%
background-color: green;
color: white;
border: 1px solid blue;
}
上述 .childBox 中的巢狀子級已設定了彈性。這和上面將彈性容器巢狀在一起 −
.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>
輸出
推廣
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP