實務上會遇到某些 Column 會指定寬度,但剩下 Column 則自動 均分
剩餘寬度,可使用 flex-grow
或 flex
實現。
Version
CSS 3
Page
flex-grow
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML Lab</title>
</head>
<body>
<main class="main">
<div class="col1">col1</div>
<div class="col2">col2</div>
<div class="col">col3</div>
<div class="col">col4</div>
<div class="col">col5</div>
</main>
</body>
<style>
.main {
display: flex;
.col1 {
width: 50px;
}
.col2 {
width: 100px;
}
.col {
flex-grow: 1;
}
}
</style>
</html>
Line 9
<main class="main">
<div class="col1">col1</div>
<div class="col2">col2</div>
<div class="col">col3</div>
<div class="col">col4</div>
<div class="col">col5</div>
</main>
col1
與col2
會實際指定寬度,但col
則會自動均分剩餘寬度
Line 21
.col1 {
width: 50px;
}
.col2 {
width: 100px;
}
col1
與col2
直接將 width 寫死
Line 29
.col {
flex-grow: 1;
}
flex-grow: 1
:設定分配剩餘寬度的比例,由於剩餘每個 column 的比例都是1
,相當於每個 column 的比例都相同,也就是平分
flex
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HTML Lab</title>
</head>
<body>
<main class="main">
<div class="col1">col1</div>
<div class="col2">col2</div>
<div class="col">col3</div>
<div class="col">col4</div>
<div class="col">col5</div>
</main>
</body>
<style>
.main {
display: flex;
.col1 {
width: 50px;
}
.col2 {
width: 100px;
}
.col {
flex: 1;
}
}
</style>
</html>
Line 29
.col {
flex: 1;
}
flex: 1
:相當於flex: 1 1 0
,展開就是:
.col {
flex-grow: 1;
flex-shrink: 1;
flex-basis: 0;
}
Conclusion
- 當每個 column 要均分時,可以不必將 width 寫死,而由
flex-grow
或flex
自動幫我們計算寬度