Featured image of post 使用 CSS 容器查詢設計模組化佈局Featured image of post 使用 CSS 容器查詢設計模組化佈局

使用 CSS 容器查詢設計模組化佈局

了解如何使用 CSS 容器查詢 (@container) 根據父元素而不是視窗尺寸建立響應式佈局。

介紹

多年來,媒體查詢 (@media) 一直是響應式網頁設計的基礎。

媒體查詢根據瀏覽器視窗的視窗寬度觸發佈局變更。然而,在現代元件驅動開發(使用 React、Vue 或 Web Components)中,基於視窗的樣式元件有明顯的限制。

例如,如果您想在較寬的主列和較窄的側邊欄中重複使用卡片元件,則媒體查詢無法偵測到該元件的可用空間,從而導致佈局中斷。

CSS 容器查詢 (@container) 透過允許您相對於其父容器的寬度設定元件的樣式來解決此限制。本文介紹容器查詢的基礎知識以及如何應用它們。


1. 視口與容器查詢

基於視窗的媒體查詢

當瀏覽器視窗調整大小時,頁面上每個與視窗連結的元素都會同時改變佈局樣式。

  • 問題: 元件樣式取決於整個視窗寬度,無論其在頁面上的位置為何。這會阻止您建立獨立的模組化 UI 元素。

基於容器的查詢

依照直接父容器的**寬度套用樣式。

  • 好處: 當放置在寬的主列中時,卡片元件可以自動呈現水平網格佈局,並在移動到狹窄的側邊欄中時交換到堆疊的垂直列表佈局 - 所有這些都在 CSS 中本地管理。

2. 基本設定和語法

實作容器查詢需要在 CSS 中執行兩個步驟:

  1. 將父元素註冊為包含查詢目標 (container-type)。
  2. 使用 @container 指令為子元素編寫樣式規則。

HTML結構

<!-- The Parent Container -->
<div class="card-wrapper">
  <!-- The Self-Contained Card Component -->
  <div class="my-card">
    <img src="thumb.jpg" alt="Thumbnail" class="card-img" />
    <div class="card-content">
      <h3>Article Title</h3>
      <p>Brief article excerpt or description text goes here...</p>
    </div>
  </div>
</div>

CSS 實現

/* 1. Register the parent element as a container query context */
.card-wrapper {
  /* Monitor the inline size (width) of the parent element */
  container-type: inline-size;
  /* Optional: Name the container context to target specific elements */
  container-name: card-container;
}

/* Default mobile/stacked card styles */
.my-card {
  display: flex;
  flex-direction: column; /* Stack vertically */
  gap: 15px;
}

/* 2. Style updates when the parent container exceeds 400px wide */
@container (min-width: 400px) {
  .my-card {
    flex-direction: row; /* Switch to horizontal row */
    align-items: center;
  }
  .card-img {
    width: 150px;
    height: 100px;
  }
}

透過此配置,只要 .card-wrapper 寬度超過 400 像素,無論瀏覽器視窗的整體大小如何,卡片都會切換到水平佈局。


3.容器查詢單元(cqw、cqh)

容器查詢也會根據父容器的尺寸引入新的 CSS 單元:

  • cqw:容器寬度的 1%。
  • cqh:容器高度的 1%。
  • cqmincqwcqh 中較小的值。
  • cqmaxcqwcqh 中的較大值。

這些單位對於根據組件的大小動態縮放版面配置非常有用:

.card-content h3 {
  /* Scale font size based on 5% of the parent container's width */
  font-size: clamp(1rem, 5cqw, 2rem);
}

結論和瀏覽器支持

CSS 容器查詢支援所有現代瀏覽器,包括 Chrome、Safari、Edge 和 Firefox。

使用容器查詢可以讓您:

  1. **減少對複雜視口媒體查詢的依賴。 **
  2. **建立適應不同佈局的可重複使用 UI 元件。 **
  3. **使用父容器單元 (cqw) 動態縮放版式。 **

考慮在 CSS 架構中採用容器查詢來建立更模組化和可維護的響應式設計。