首頁  >  文章  >  web前端  >  移动端优先策略下的css如何编写_html/css_WEB-ITnose

移动端优先策略下的css如何编写_html/css_WEB-ITnose

WBOY
WBOY原創
2016-06-21 08:55:311131瀏覽

移动互联网时代,如何开发一个响应式站点,是每一个前端人员必备的技能。通常,我们能意识到良好的设计对移动端开发的重要性,但是在代码层面很少讨论。

接下来,让我们搞清楚:

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/


陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn