什麼是 flex
?
flex 是一個簡寫屬性,可以按照次序定義一個 flex item
的 flex-grow(必填), flex-shrink(選填) 和 flex-basis(選填) 的屬性值。
<div class="container">
<div class="item pink"></div>
</div>
.container {
display: flex;
}
.item {
height: 100px;
}
.pink {
background-color: pink;
width: 50px;
flex: 1 100px; /* flex-grow: 1; flex-basis: 100; */
}
flex: initial
= flex: 0 1 auto
(default)
<div class="container">
<div class="item olive"></div>
</div>
.container {
display: flex;
}
.item {
height: 100px;
}
.olive {
background-color: olive;
width: 50px;
flex: initial;
/* flex-grow: 0; flex-shrink: 1; flex-basis: auto; */
}
flex: auto
= flex: 1 1 auto
<div class="container">
<div class="item red"></div>
</div>
.container {
display: flex;
}
.item {
height: 100px;
}
.red {
background-color: red;
width: 50px;
flex: auto;
/* flex-grow: 1; flex-shrink: 1; flex-basis: auto; */
}
flex: none
= flex: 0 0 auto
<div class="container">
<div class="item blue"></div>
</div>
.container {
display: flex;
}
.item {
height: 100px;
}
.blue {
background-color: blue;
width: 50px;
flex: auto;
/* flex-grow: 0; flex-shrink: 0; flex-basis: auto; */
}
flex: 1 0 auto;
<div class="container">
<div class="item green"></div>
</div>
.container {
display: flex;
}
.item {
height: 100px;
}
.green {
background-color: blue;
width: 50px;
flex: auto;
}
flex-basis
定義 flex item 初始長度
如果 flex-basis 為 auto ,代表 flex-basis 的長度由內容決定。
flex-grow
當 flex container 大於 flex-item 初始長度總和,依 flex-grow 定義flex item 剩餘空間的分配。
*剩餘空間 = flex container 長度 - flex item 初始長度總和 *
flex-shrink
當 flex container 小於 flex-item 初始長度總和,依 flex-shrink 定義 flex item 壓縮空間的分配。
*壓縮空間 = flex item 初始長度總和 - flex container 長度 *
如果不希望 flex item 被壓縮:flex-shrink: 0
flex
flex
深入理解css3中的flex-grow、flex-shrink、flex-basis
Understanding Flex Shrink, Flex Grow, and Flex Basis, and using these properties to their full potential
Designing A Product Page Layout with Flexbox