自學日記

學習程式相關知識及學習法

0%

CSS 響應式網頁(RWD)

CSS 響應式網頁(RWD)

介紹響應式網頁(RWD)

響應式網頁

以一個終端頁面,去顯示效果並適應在不同大小的界面上,以%或em作為單位。

為什麼需要RWD

  1. 更好的使用者體驗
  2. RWD vs 手機版網站
  3. 已成趨勢

    @media媒體查詢

    在製作 RWD 響應式網頁時,一定會用到的 CSS 語法就是 media,代表的就是針對指定的「媒體」設定樣式。

視窗或頁面尺寸 ( Viewport/Page Dimensions )

如何使用@media

HTML

1
2
3
4
5
//單純給予裝置
<link rel="stylesheet" media="screen" href="style.css" />

//給予裝置與條件
<link rel="stylesheet" media="screen and (min-width: 400px) and (max-width: 700px)" href="style.css" />

CSS

1
2
3
@media screen {
* { font-family: sans-serif; }
}

css中更進一步使用方式:or、and、not、only

  • OR
  1. 判斷於螢幕尺寸及Media類型時:
    EX.螢幕尺存小於等於 400px 「或」印刷時,字體會變成紅色 100px,反之就是黑色 30px。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    h1{
    font-size:30px;
    }
    @media (max-width:400px), print{
    h1{
    font-size:100px;
    color:red;
    }
    }
  2. 透過 orientation 判斷裝置是直立或橫放:
    EX.裝置是直立「或」寬度小於 200px,就讓文字變成紅色 50px。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    h1{
    font-size:30px;
    }
    @media (orientation: portrait), (max-width:200px){
    h1{
    font-size:50px;
    color:red;
    }
    }
  • AND
    使用 AND 必須要所有條件皆滿足:
    EX.「螢幕」大小介於「200px~300px」之間時,字體會是紅色 50px。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    h1{
    font-size:30px;
    }
    @media screen and (min-width:200px) and (max-width:300px){
    h1{
    font-size:50px;
    color:red;
    }
    }

AND 和 OR 也可以互相搭配使用

  • NOT
    NOT 的目的在於排除一些裝置媒體,會寫在 media query 的字首:
    EX.除了彩色螢幕之外的裝置,都套用 example.css,這裡要注意一下,NOT 和 ONLY 後方都必須先接 media type ( 像是 screen 或 print ),不然會沒有作用。
    1
    <link rel="stylesheet" media="not screen and (color)" href="example.css" />

NOT 可以使用逗號分隔,就能做出不同的判斷

1
2
3
4
5
6
@media not screen and (max-width:300px), print and (orientation: landscape){
h1{
font-size:...px;
color:...;
}
}
  • ONLY

min-width 與 max-width

最須注意這個概念:

max-width,表示這個數字以下(包含) 的都適用。(<=)
min-width,表示這個數字以上(包含) 的都適用。(>=)

RWD 響應式網頁單位

我們常在寬高設定單位上會使用百分比(%)和像素(px),如以px為單位是我們一般習慣的,但在不同裝置下,隨著營幕像素大小不同,這時就可以改用rem為單位,或者更新的單位vhvm

rem使用方式

概念: 指相對於根元素的字體大小的單位
通常設置1rem=10px
EX.

1
2
3
4
5
6
7
html{
font-size: 10px;
}
/* 通常設置1rem=10px 所以上方html設置後,下方1rem=10px*/
div{
font-size: 1rem;
}

VH、VW

vh是view height,指螢幕可視範圍高度的百分比;vw則是view width,指螢幕可是範圍寬度的百分比,優點為隨著瀏覽器的縮放而改變。

參考資料:
CSS Media Queries 詳細介紹Day22:小事之 Media Query認識CSS3的新單位vh、vw響應式佈局的常用解決方案對比(媒體查詢、百分比、rem和vw/vh)