2

我想知道在 CSS 中对规则进行分组可能会对解析和渲染性能产生什么影响。

方法一:

.class1 {
  margin: 10px;
  padding: 20px;
  color: #ccc;
}
.class2 {
  margin: 10px;
  padding: 30px;
  color: #ddd;
}
.class3 {
  margin: 20px;
  padding: 30px;
  color: #eee;
}
.class4 {
  margin: 20px;
  padding: 20px;
  color: #fff;
}

与方法2:

.class1,
.class2 {
  margin: 10px;
}
.class3,
.class4 {
  margin: 20px;
}
.class1,
.class4 {
  padding: 20px;
}
.class2,
.class3 {
  padding: 30px;
}
.class1 {
  color: #ccc;
}
.class2 {
  color: #ddd;
}
.class3 {
  color: #eee;
}
.class4 {
  color: #fff;
}

当然,我们讨论的是具有相同规则分组的大型 css 文件,因此有时相同的选择器会被分割成很多块。

它对 CSS 解析和渲染的影响是否足以放弃这种方法以支持更大的文件,但更清洁并在一个选择器中收集所有规则?

选择器匹配可能很昂贵。在现实生活中,这些选择器中的每一个都不仅仅是一个类,而是 2-3 个嵌套类。因此对于每个元素,浏览器必须匹配选择器三次才能应用所有规则。首先是边距,然后是填充,然后应用颜色。第二种方法似乎非常昂贵。

4

3 回答 3

2

我准备了两个带有两个选项的代码笔:

方法 1(每个类一个选择器) - https://codepen.io/kali187/pen/EvpVdb - (仅输出:https://codepen.io/kali187/live/EvpVdb

@for $n from 1 through 2000 {
  .div-#{$n} {
      float: left;
      background: rgb( $n, $n, $n );
      height: 10px + 1px * $n / 2;
      width: 20px + 1px * $n / 5;
      margin: 0 1px 1px 0;
      border: 1px solid #f00;
  }
}

方法2(一个类的多个选择器) - https://codepen.io/kali187/pen/dzjGPa - (只是输出:https://codepen.io/kali187/live/dzjGPa

$max: 1000;

@for $i from 1 through $max {
  %bg-#{$i} {
    background: rgb( $i, $i, $i );
  }
  %width-#{$i} {
    width: 20px + 1px * ceil($i / 5);
  }
  %height-#{$i} {
    height: 20px + 1px * ceil($i / 3);
  }
}

@for $n from 1 through (2*$max) {
  .div-#{$n} {
      float: left;
      @extend %bg-#{ceil($n/2)};
      @extend %width-#{ceil($n/3)};
      @extend %height-#{ceil($n/4)};
      margin: 0 1px 1px 0;
      border: 1px solid #f00;
  }
}

第一种方法的渲染结果: 在此处输入图像描述 解析样式和 html ~ 25ms

第二种方法的渲染结果: 在此处输入图像描述 解析样式和 html ~ 75ms (3 倍长)

如果有人想测试它,请做

于 2017-08-24T10:52:21.357 回答
0

如果项目中很多地方有相同的属性,添加类。或组。

于 2017-08-24T10:43:41.127 回答
0

团体。这使您的 CSS 文件整洁明了。它也可以提高您的渲染性能。一遍又一遍地写同样的东西不是一个好习惯。

于 2017-08-24T09:32:04.600 回答