CSS Flexbox 排版
什麼是 Flexbox?
比喻:Flexbox 就像把物品排在架子上 📐
你決定架子是橫的還是直的、物品怎麼對齊、間距怎麼分配。
啟用 Flexbox
.container {
display: flex; /* ← 啟用 Flex 佈局 */
}
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
容器屬性(父元素)
.container {
display: flex;
/* 主軸方向 */
flex-direction: row; /* → 水平(預設) */
flex-direction: row-reverse; /* ← 水平反轉 */
flex-direction: column; /* ↓ 垂直 */
flex-direction: column-reverse; /* ↑ 垂直反轉 */
/* 換行 */
flex-wrap: nowrap; /* 不換行(預設) */
flex-wrap: wrap; /* 換行 */
/* 主軸對齊 */
justify-content: flex-start; /* 靠左(預設) */
justify-content: flex-end; /* 靠右 */
justify-content: center; /* 置中 */
justify-content: space-between; /* 兩端對齊,中間平均分配 */
justify-content: space-around; /* 每個元素兩側等距 */
justify-content: space-evenly; /* 所有間距完全相等 */
/* 交叉軸對齊 */
align-items: stretch; /* 拉伸填滿(預設) */
align-items: flex-start; /* 頂部對齊 */
align-items: flex-end; /* 底部對齊 */
align-items: center; /* 垂直置中 */
/* 間距 */
gap: 16px; /* 元素之間的間距 */
gap: 16px 24px; /* 列距 欄距 */
}
子元素屬性
.item {
/* 伸展比例 */
flex-grow: 1; /* 佔剩餘空間的比例(0=不伸展) */
/* 收縮比例 */
flex-shrink: 0; /* 空間不足時不縮小 */
/* 基本大小 */
flex-basis: 200px; /* 預設大小(替代 width) */
/* 簡寫 */
flex: 1; /* = flex-grow:1 flex-shrink:1 flex-basis:0% */
flex: 0 0 200px; /* 不伸展、不收縮、固定 200px */
/* 個別對齊 */
align-self: center; /* 覆蓋容器的 align-items */
/* 排序 */
order: -1; /* 排最前面(預設 0) */
}
常見佈局
/* 水平垂直置中 */
.center {
display: flex;
justify-content: center; /* 水平置中 */
align-items: center; /* 垂直置中 */
height: 100vh;
}
/* 等寬三欄 */
.three-cols {
display: flex;
gap: 16px;
}
.three-cols > div {
flex: 1; /* 三個都 flex:1 = 等分 */
}
/* 側邊欄 + 主內容 */
.layout {
display: flex;
}
.sidebar {
flex: 0 0 250px; /* 固定 250px,不伸縮 */
}
.main {
flex: 1; /* 佔剩餘空間 */
}
/* 底部固定 footer */
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main {
flex: 1; /* 主內容撐滿 → footer 自然在底部 */
}
Navbar 實例
.navbar {
display: flex;
justify-content: space-between; /* Logo 靠左,選單靠右 */
align-items: center;
padding: 0 24px;
height: 60px;
background: #1a1a2e;
}
.nav-links {
display: flex;
gap: 24px;
list-style: none;
}