iT邦幫忙

0

跟著AI一起:從零打造一個互動式網站 Day7

wqq 2025-09-26 09:21:42112 瀏覽
  • 分享至 

  • xImage
  •  

Flexbox 與 Grid

網頁排版最常用的是 Flexbox 和 Grid。

Flexbox 的特點:

適合「一條線」的排列(橫排或直排)。

  • 對齊與間距設定非常靈活。
  • 用來在一行或一列中排列元素。
  • justify-content:控制 主軸對齊(預設是橫向)。
  • align-items:控制 交叉軸對齊(預設是垂直)。

其他對齊方式

  • justify-content: flex-start; → 全靠左
  • justify-content: center; → 全置中
  • justify-content: space-around; → 元素左右有等距間隔
  • align-items: flex-end; → 底部對齊

常用屬性
css:

.container {
  display: flex;
  justify-content: space-between; /* 左右分散 */
  align-items: center; /* 垂直置中 */
}
.item {
  width: 100px;
  height: 100px;
  background: lightblue;
}

HTML:

<div class="container">
  <div class="item">A</div>
  <div class="item">B</div>
  <div class="item">C</div>
</div>

Grid 的特點:

  • 適合「二維」排版,可以同時控制列和欄。
  • 非常適合複雜的網頁版面(例如報章雜誌排版)。
    css:
.grid {
  display: grid;/* 啟用 Grid */
  grid-template-columns: 1fr 1fr 1fr; /* 三欄 */
  grid-template-rows: auto auto; /* 兩列,高度自動 */
  gap: 10px; /* 格子之間的間距 */
}
.box {
  background: lightgreen;
  padding: 20px;
}

HTML:

<div class="grid">
  <div class="box">1</div>
  <div class="box">2</div>
  <div class="box">3</div>
</div>

(進階用法:跨欄/跨列)

.box1 {
  grid-column: 1 / 3; /* 從第1欄跨到第3欄 */
  grid-row: 1 / 2;   /* 佔據第一列 */
}

💡 使用時機:

複雜的版面(首頁 layout、作品集展示)

優雅控制區塊大小

Flex vs Grid 怎麼選?

如果只是「橫向/直向排一排」例如:導覽列 → Flexbox

如果需要「網格型的結構」例如:相簿展示頁 → Grid

🔹小練習

做一個「三欄卡片排版」:

<div class="grid">
  <div class="card">卡片 1</div>
  <div class="card">卡片 2</div>
  <div class="card">卡片 3</div>
</div>

.grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三等分 */
  gap: 20px;
}
.card {
  background: #f5f5f5;
  padding: 20px;
  border: 1px solid #ccc;
}

結果:三個卡片會平均分配版面,適合做「最新文章」、「商品展示」。


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言