Skip to content

RWD - 最佳實踐

在進行 響應式網頁設計 (Responsive Web Design, RWD) 時,除了懂得使用 Media Query 和彈性佈局之外,真正讓一個網站既美觀又實用,靠的是一系列「最佳實踐」。

這些原則可以幫助您開發出跨裝置、跨瀏覽器都能順暢運行的網站,提升可讀性、可用性與效能。

核心概念

彈性容器

使用相對單位,如: %emrem,而非固定像素來定義佈局。

css
.container {
  width: 100%;
  max-width: 1200px;
  margin-left: auto;
  margin-right: auto;
}

.column {
  width: 50%; /* 使用百分比而非固定像素 */
}

響應式影像

讓影像能夠縮放以適應容器的變化。

css
.img-resp {
  max-width: 100%;
  height: auto;
}

媒體查詢

根據不同條件套用不同的 CSS 樣式。

css
/* 手機 */
@media screen and (max-width: 768px) {
  .column {
    width: 100%;
  }
}

/* 平板 */
@media screen and (min-width: 769px) and (max-width: 1024px) {
  .column {
    width: 50%;
  }
}

設計策略

Desktop First 桌機優先

先設計桌機版,再縮減到小螢幕:

css
/* 預設(桌機版)樣式 */
.wrapper {
  display: flex;
}

.sidebar {
  width: 25%;
}

.content {
  width: 75%;
}

/* 平板 */
@media screen and (max-width: 1024px) {
  .sidebar {
    width: 30%;
  }
  
  .content {
    width: 70%;
  }
}

/* 手機 */
@media screen and (max-width: 768px) {
  .wrapper {
    flex-direction: column;
  }

  .sidebar,
  .content {
    width: 100%;
  }
}

Mobile First 行動優先

先設計手機版,再逐步擴展到更大螢幕:

css
/* 預設(手機版)樣式 */
.container {
  padding: 10px;
}

/* 手機版隱藏選單 */
.nav-menu {
  display: none;
}

/* 平板以上 */
@media screen and (min-width: 768px) {
  .container {
    padding: 20px;
  }
  
  .nav-menu {
    display: block;
  }
}

/* 桌機版 */
@media screen and (min-width: 1024px) {
  .container {
    padding: 40px;
  }
}

內容優先

css
/* 重要內容優先顯示 */
.important-content {
  order: -1; /* 在 Flexbox 中優先顯示 */
}

@media screen and (max-width: 768px) {
  .secondary-content {
    display: none; /* 手機版隱藏次要內容 */
  }
}

觸控友善設計

增大可點擊區域。

css
.touch-target {
  min-height: 44px;
  min-width: 44px;
  padding: 12px;
}

增加按鈕間距。

css
.button-group .button {
  margin: 5px;
}

效能考量

使用 CSS 處理簡單動畫。

css
.menu-toggle {
  transition: transform 0.3s ease;
}

避免在小螢幕載入大圖片。

css
@media screen and (max-width: 768px) {
  .hero-image {
    background-image: url('small-image.jpg');
  }
}

@media screen and (min-width: 769px) {
  .hero-image {
    background-image: url('large-image.jpg');
  }
}

響應式影像

<picture> 是一個新的 HTML5 標籤,不需要 Javascript、也不需要 CSS,單純 HTML5 就可以達成響應式圖片的設定。<source> 是用於載入圖片,相關的設定如下:

  • srcset: 指定替代圖片的路徑。
  • media: 媒體查詢。
  • type: 指定替代圖片的格式,如果不符合,就執行下一個。
html
<picture>  
  <source media="(min-width: 1201px)" srcset="./images/1920.jpg">  
  <source media="(min-width: 1025px)" srcset="./images/1200.jpg">  
  <source media="(min-width: 769px)" srcset="./images/1024.jpg">  
  <source media="(min-width: 415px)" srcset="./images/768.jpg">  
  <source media="(max-width: 414px)" srcset="./images/414.jpg">  
  <img class="img-resp" src="./images/1920.jpg" alt="">  
</picture>

小提醒

  • <source> 的順序很重要、瀏覽器會直接使用第一個符合的 <source> 而忽略掉後續的標籤。
  • 最後再指定一個 <img> 元素作為 <picture> 標籤中的預設圖片、當瀏覽器不支援 <picture> 標籤或是沒有符合的 <source> 時,則直接顯示 <img>