css - LESS.JS CSS 中的冗余,使用 Mixins 而不是选择器继承?

标签 css coding-style syntax less

我在使用 less.js 的同时经常使用 mixins。例如。我确实有一个像这样的基本类“gradientBlack”。

.gradientBlack {
    background: #333333;
    background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
    background: -webkit-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
    background: -o-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
    background: -ms-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#5a5a5a', endColorstr='#000000', GradientType=0 );
    background: linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
} 

然后我在几个定义中重用这个类,比如

h3 {
    .gradientBlack;
    ...
}
.darkBox {
    .gradientBlack;
    ...
}

这种方法的一个缺点是,它用冗余定义使 CSS 膨胀。例如。计算出的 CSS 可能与此类似。

h3 {
    background: #333333;
    background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
    //... and maybe some more (redundant) definitions

}

.darkBox {
    background: #333333;
    background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #5a5a5a), color-stop(60%, #333333), color-stop(100%, #000000));
    //... and maybe some more (redundant) definitions
}

对于像我这样使用大量渐变、圆 Angular 等的人来说,这会很快加起来。

问题(已编辑)

我发现该主题的已知名称是选择器继承(请参阅 Sass )并且目前似乎尚未实现。讨论用法和优点here .此语法的计算 css 可能如下所示。

h3,
.darkBox,
.gradientBlack {
    background: #333333;
    background: -moz-linear-gradient(top, #5a5a5a 0%, #333333 60%, #000000 100%);
    ...
}

尽管如此,我将不胜感激任何建议,何时打扰,何时不打扰 - 以及任何其他主题提示,只要选择器继承不是一个选项,如何继续。

最佳答案

我觉得有几个问题需要考虑:

  • 样式表的大小
  • 样式表执行效率(浏览器执行速度)
  • 样式表的可维护性
  • 标记的可维护性 (html)

Mark Gemmill 提倡的方法(在/3 中)实际上是 Nicole Sullivan's Object Oriented CSS .在切换到 Sass 之前,我使用了该模式,并且仍然发现其中一些有用,但我认为 Sass/Less 方法会导致更易于维护的 CSS 和更易于维护的标记 - 无需在整个标记中散布表示类。

我认为 @extend(选择器继承)是 Sass 相对于 Less 的主要优势之一,它确实减少了编译样式表中的冗余。

对我来说,更易于维护的 CSS 和标记的好处超过了稍微大一点的样式表的任何缺点。我想你会发现,如果你保留你的 selectors efficient (不要过多地嵌套在 Less/Sass 中)并在生产中进行组合和最小化,性能影响将比您想象的要小。

关于css - LESS.JS CSS 中的冗余,使用 Mixins 而不是选择器继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557626/

相关文章:

jqueryui 拖拽移除列表图标

jquery - 更改 div 中的文本

c - 为什么C文件会以/*[]*/结尾

wpf - 如何在 WPF DataGrid 中垂直居中行的内容?

java - "instanceof List"和 'o instanceof List<?>"的区别

vim - Linux/Ubuntu 目录位置 ~/.vim/syntax/

java - Java中的 "->"运算符是什么?甚至是运营商吗?

javascript - 如何在JS中的 "for of"循环中嵌入if语句

html - 用于地址验证的网页美学

c++ - 如何在不使用 'using' 的情况下缩短 C++ 头文件中的 namespace 缩进?