☕ NEW! 完成新手任務即可參加抽獎!LINE 星巴克禮券等你拿,名額有限!        🎉 推廣活動:邀請好友註冊 DevLearn,累積推薦抽 LINE 星巴克禮券! 活動詳情 →        🔥 活動期間 2026/4/1 - 5/31 |已有 0 人參加       
html 初學

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 {
    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;
}

💡 大家的想法 · 0

載入中...
💬 即時聊天室 🟢 0 人在線
😀 😎 🤓 💻 🎮 🎸 🔥
➕ 新問題
📋 我的工單
💬 LINE 社群
🔒
需要註冊才能使用此功能
註冊帳號即可解鎖測驗、遊戲、簽到、筆記下載等所有功能,完全免費!
免費註冊