分别为每个@media嵌套class规则是一种好习惯还是创建@media并将所有类嵌套在其中更好?
就加载页面的速度而言,哪种方法更有效?

/*
 * Sass or Less
 */

/* example_1 */
.class1 {
  width: 100%;

  @media screen and (min-width: 740px) {
    width: 50%;
  }
}

/* example_2 */
.class1 {
  width: 100%;
}

.class2 {
  color: #000;
}

@media screen and (min-width: 740px) {
  .class1 {
    width: 50%;
  }

  .class2 {
    color: #faa;
  }
}

最佳答案

我认为这取决于要编写的代码量。它可以正常工作,但是嵌套在每个类中的数百个不同的媒体查询可能很难维护。在我看来,一个很好的做法(尤其是对于大型项目)是对每个媒体查询阈值使用单独的文件,以使CSS尽可能地井井有条。
例如:

无样式

.class1 {
  width: 100%;
}

.class2 {
  color: #000;
}

@media screen and (min-width: 740px) {
  @import "min740.less";
}


min740.less

.class1 {
  width: 50%;
}

.class2 {
  color: #faa;
}


如果要编写单独的组件(如按钮或印刷字体),则可以将所有相关的媒体查询保留在同一文件中,以便拥有一个完全独立的CSS模块(基本上是第二个示例)。

在速度和性能方面,显然始终建议在生产中使用编译后的LESS,但是考虑到您的示例,单个媒体查询选择器会更高效,因为以“ example1方式”,媒体查询选择器将被重复多次:

.class1 {
  width: 100%;
}
@media screen and (min-width: 740px) {
  .class1 {
    width: 50%;
  }
}
.class2 {
  width: 100%;
}
@media screen and (min-width: 740px) {
  .class2 {
    width: 50%;
  }
}

09-25 18:39
查看更多