# CSS RWD ## viewpoint 必備基礎設定 ```css=! <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"> ``` ## 設定斷點 好用網站 - [mydevice.io](https://www.mydevice.io/) ```css=! @media screen and (max-width: 1200px){  } /* 螢幕小於 1200 時 */ ``` ## 常見RWD排版設定集合(各自獨立) * vw & vh會以螢幕寬度和高度做為百分比自動調整字體大小,因手機寬高差異不大,可用vw & vh做為通用設定;PC則還是用px。 * 若PC版有用float;手機版可利用 float:none 將排版轉換為垂直排列。 ```css=! .wrapper{  width: 100%; /* 將網頁寬度調整為device寬度 */ height: 100vh; /* 依據瀏覽器高度做百分比換算 */ } header{ background-size: cover;} img{ /* 將2張圖片水平排列 */ display: block; width: calc(50% - 5px); /* 扣除間距、margin等 */ } .xxx{ flex-direction: column;} /* 將水平排列,調整為垂直排列 */ html{ font-size: 62.5%;} /* 預設字體大小16px的 62.5% 為 10px */ h3{ font-size: 2.5rem;} /* 以html制定的font-size為依據 */ ``` ## 往左展開的漢堡選單 ```css=! .topMain { width: auto; position: relative; /* position定位起手式 */ } .topMain .fa { display: block; /* 顯示隱藏的漢堡圖示 */ position: absolute; right: 0; top: 0; /* 定位顯示的漢堡圖示 */ } .topMain ul { float: none; position: fixed; /* 蓋板一律用position: fixed */ height: 100%; right: -300px; top: 60px; /* 定位ul的起始位置 */ transition: all .5s; /* 設定動畫持續時間 */ } .topMain li { float: none;} .topMain .fa:hover ~ ul { right: 0;} /* 定位被hover後的ul位置 */ ``` ## HTML5圖片替換 * 程式會由上往下執行,一旦符合條件,就會跳過後面的程式碼。故寫code的順序,必須為media由小到大,最後再放PC版要用的img。 ```css=! <picture> <source srcset="ab_small.png" media="(max-width: 414px)"> <source srcset="ab_middle.png" media="(max-width: 768px)"> <img src="ab_big.png" alt=""> </picture> ``` ## YouTube影片寬高隨裝置縮放 * 網頁元件中,只有img會自動等比例縮放。 * 當物件padding使用百分比時,會依據父層高度計算;故可將父層設為width: 100%,並運用padding-bottom(或top)將高度撐開,放置影片的div就會在父層縮放時自動等比例縮放了。 ```css=! div.movie { width: 100%; height: auto; /* 或設為 0 */ padding-bottom: 56.25%; /* 長寬比為16:9 */ position: relative; } div.movie iframe { position: absolute; left: 0; top: 0; } ``` ###### tags: `frontend` `cssmonster` [:arrow_right: Back to Front End Homepage :arrow_left:](/S-c0eqQmS16D8tcTx4ae1g)