依大小設定樣式

網頁功能: 容器查詢 (大小)

總覽

感知大小的樣式設定可讓元件根據可用空間 (而非整個螢幕的大小) 變更版面配置或外觀。這項功能適用於可能放置在版面配置不同部分 (例如窄側欄或寬主區域) 的元件,例如資訊卡或導覽列。

建議使用容器查詢,因為這能讓元件真正模組化。您不需要知道元件的位置,也不需要編寫複雜的媒體查詢來處理所有可能的版面配置。

導入作業

1. 定義容器

必要:您必須先告知瀏覽器要評估哪個容器元素。

.card-container {
  /* Define the container type. Use 'inline-size' for width-based queries. */
  /* You can also use 'size' for both width and height, but it requires explicit sizing. */
  container-type: inline-size;
}

2. 根據容器大小套用樣式

使用 @container 規則,在容器達到特定大小時套用樣式。

/* Default styles for small containers (stacked layout) */
.card {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

/* Styles for larger containers (side-by-side layout) */
/* This triggers when the container is wider than 400px */
@container (min-width: 400px) {
  .card {
    flex-direction: row;
    align-items: center;
  }
  
  .card-image {
    width: 150px;
    height: 150px;
  }
}

3. 依條件顯示內容

您也可以使用容器查詢,在空間較大時隱藏或顯示額外詳細資料。

.card-details {
  /* Hide extra details by default in small spaces */
  display: none;
}

@container (min-width: 600px) {
  .card-details {
    /* Show details when there is plenty of room */
    display: block;
  }
}

備用策略

如果瀏覽器不支援容器查詢,最好的做法是使用安全的預設版面配置 (例如堆疊垂直版面配置),並在一般螢幕大小允許的情況下,使用媒體查詢逐步漸進增強。

/* Default safe stacked layout */
.card {
  display: flex;
  flex-direction: column;
}

/* Fallback using media queries for older browsers */
@media (min-width: 600px) {
  .card {
    flex-direction: row;
  }
}

/* Overwrite with container queries where supported */
@supports (container-type: inline-size) {
  @media (min-width: 600px) {
    .card {
      /* Reset media query fallback if needed, or let container query handle it */
      flex-direction: column;
    }
  }
  
  @container (min-width: 400px) {
    .card {
      flex-direction: row;
    }
  }
}

這樣一來,即使版面配置無法完美適應每個特定容器寬度,使用舊版瀏覽器的使用者仍可看到可用的版面配置。