【问题标题】:Is it better to use mixins or combined sets of styles in stylesheets?在样式表中使用 mixins 或组合样式集更好吗?
【发布时间】:2017-08-11 23:29:30
【问题描述】:

我想知道哪种编码样式表的方式在性能、可读性和日常用例方面更好。

假设我们要制作样式:

.container {
  background-color: red;
  .nested-container {
    color: blue;
  }
}

.container-two {
  background-color: black;
  .nested-container {
    color: blue;
  }
}

我想知道哪种方式对这种情况更有效。

/* mixins way */
@mixin duplicated-container {
  .nested-container {
      color: blue;
  }
}

.container {
  background-color: red;
  @include duplicated-container;
}
.container-two {
  background-color: black;
  @include duplicated-container;
}

/* combined sets way */
.container {
    background-color: red;
}
.container-two {
    background-color: black;
}
.container,
.container-two {
  .nested-container {
    color: blue;
  }
}

第一种方式更具可读性,至少对我而言。 第二种方式使输出文件比使用mixins 时更小,因为代码不会以任何方式重复。

请记住,这只是我想要实现的非常简单的示例,如果 containercontainer-two 在文件中的两个不同位置,第一种方法使它非常易读且易于使用,但它在最终输出中重复了代码,所以我不确定以这种方式使用mixins 是否好。

过去几天这对我来说是个大难题,我决定向专业人士寻求帮助,因为我总是以凌乱的样式表告终。 我感谢所有帮助。

【问题讨论】:

  • 如果您担心文件大小,请使用 CSS 压缩器/压缩器。可以为任何一个的可读性做一个案例。视情况而定。
  • 感谢您的回答。我已经使用CSS Minifier。问题是如果这个mixin 是 50 行代码,我们最终会得到 50 行乘以我们在代码中使用它的数量,在第二种情况下,我们最终只有 50 行代码。这对我来说很难破解。

标签: css sass nested mixins


【解决方案1】:

第一个似乎是更好的选择,因为类被列在一个地方

使用第二种方法,一旦您添加了 .container-three,您必须记住将其添加到 .nested-container 从中获取其样式的类列表中。

在使用 mixin 时,您不必担心文件大小。由于大多数服务器默认使用现代的 CSS 压缩器和 gzip 压缩内容管道,因此在 CSS 中复制内容不会显着增加文件大小,might even perform better

不用担心重复代码。这是一个微优化,无论如何都会被 gzip 大量优化。在这种情况下寻求可读性。

【讨论】:

  • 这是一篇非常好的文章,为我澄清了很多!非常感谢您和您的时间!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-30
  • 2021-09-29
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 2021-12-31
相关资源
最近更新 更多