接下來,讓我們搞清楚:
1,什么是移動端優先策略(小屏優先策略)
2,這種策略的樣式如何編寫。
移動端優先策略VS桌面端優先策略
移動端優先策略:以適配移動端設備為首要目標進行設計開發,盡可能的適配桌面端大屏。
桌面端優先策略:以桌面端設備作為首要考慮目標,移動端放到次要位置考慮
這里就是一個主次關系的考慮。
在移動端優先策略下樣式的編寫,我們可以借用媒體查詢來完成對于桌面端大屏設備的適配(例如min-width)。
舉個例子:
// This applies from 0px to 600px
body {
background: red;
}
// This applies from 600px onwards
@media (min-width: 600px) {
body {
background: green;
}
}
這里,body在600px一下的寬度時,背景色為紅色,而超過600px,就變為綠色了。
在桌面端優先的策略下,我們要這么寫css:
// This applies from 600px onwards
body {
background: green;
}
// This applies from 0px to 600px
@media (max-width: 600px) {
body {
background: red;
}
}
為什么要采用移動端優先的策略?
相對于小屏幕,為了適配大屏幕,我們的css代碼通常要復雜一些,所以移動端優先的策略有利于精簡代碼。
考慮如下場景:
一個站點有個如下布局,.Content在移動端占據100%,在桌面端占據60%
此時,對于小屏幕,我們可以借助屬性的默認值為content區域添加樣式,比如一個div,默認情況下,作為塊級元素默認寬度為100%。
小屏優先策略下的sass代碼:
.content {
// Properties for smaller screens.
// Nothing is required here because we can use the default styles
// Properties for larger screens
@media (min-width: 800px) {
float: left;
width: 60%;
}
}
大屏優先策略下:
.content {
// Properties for larger screens.
float: left;
width: 60%;
// Properties for smaller screens.
// Note that we have to write two default properties to make the layout work
@media (max-width: 800px) {
float: none;
width: 100%;
}
}
看看,我們節省了2行代碼,減少了點腦力消耗,想想,如果實在大項目中,這會有更大的益處吧。
移動端優先策略下,我們如何使用Max-width
當你想要將樣式的應用目標限定在某一特定的視口寬度時,max-width就派上用場了,結合min-width的使用,還可以創造一個限定區間。
考慮一個縮略圖展示頁的布局:800px以下的視口寬度時,顯示為3列,否則為4列
當這些縮略圖之間沒有間隙時,很簡單:
.gallery__item {
float: left;
width: 33.33%;
@media (min-width: 800px) {
width: 25%;
}
}
實際情況下,通常是有間距的,情況就變的復雜了:
很容易想到如下的css:
.gallery__item {
float: left;
width: 30.333%;
margin-right 5%;
margin-bottom: 5%;
&:nth-child(3n) {
margin-right: 0;
}
@media (min-width: 800px) {
width: 21.25%; // (100% - 15%) / 4
&:nth-child (4n) {
margin-right: 0;
}
}
}
但是因為,我們設定了在每個第三項,margin-right為0,而當一行有4項時,應該是每個第四項為0,我們可以考慮通過重寫的方式解決:
.gallery__item {
// ...
@media (min-width: 800px) {
// ...
&:nth-child (3n) {//恢復第三項的間距
margin-right: 5%;
}
&:nth-child(4n) {
margin-right: 0%;
}
}
}
這個方式并不是太好,因為當我們需要在更大的屏幕上顯示更多的項時,我們會遇到同樣的問題。
考慮如下方式,把隨視口變化的東西放到相應的查詢語句中,默認樣式只保留公共的部分,能減少重寫帶來的麻煩:
.gallery__item {
float: left;
margin-right: 5%;
margin-bottom: 5%;
@media (max-width: 800px) {
width: 30.333%;
&:nth-child(3n) {
margin-right: 0;
}
}
@media (min-width: 800px) {
width: 21.25%; // (100% - 15%) / 4
&:nth-child (4n) {
margin-right: 0;
}
}
}
參考: http://zellwk.com/blog/how-to-write-mobile-first-css/
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com