各种选项,没有固定答案
这在很大程度上取决于您的代码、您的目标等,以及您如何为各种元素获取样式。以下是一些可能性,每种可能性都有优点和缺点。
1. Mixin(你目前所做的)
少
.inputbase() {
/* your base code */
}
.someInput {
.inputbase;
/*some input special code */
}
.someOtherInput {
.inputbase;
/*some other input special code */
}
.andAnotherInput {
.inputbase;
/*and another input special code */
}
CSS 输出
.someInput {
/* your base code */
/*some input special code */
}
.someOtherInput {
/* your base code */
/*some other input special code */
}
.andAnotherInput {
/* your base code */
/*and another input special code */
}
如果.inputbase() 中的代码多于一两行,并且混合在多个实例中,则会产生大量额外代码。这是您发现自己面临的问题。
2。扩展一个类
看起来LESS is just about ready to allow for extending mixins,但目前(LESS 1.5)这只需要一个类定义,所以这样:
少
.inputbase {
/* your base code */
}
.someInput {
&:extend(.inputbase);
/*some input special code */
}
.someOtherInput {
&:extend(.inputbase);
/*some other input special code */
}
.andAnotherInput {
&:extend(.inputbase);
/*and another input special code */
}
CSS 输出
.inputbase, /* this is gone once mixin extending allows .inputbase() extension */
.someInput,
.someOtherInput,
.andAnotherInput {
/* your base code */
}
.someInput {
/*some input special code */
}
.someOtherInput {
/*some other input special code */
}
.andAnotherInput {
/*and another input special code */
}
优点是所有基本代码不重复,但重复的是选择器,因为它们首先与基本代码组合在一起,然后再次为单个代码输出。如果有人喜欢将他们的代码分组在一个选择器定义中,那么这不是要走的路。否则,这提供了一种减少 CSS 输出的好方法。
3.两个类(您建议的额外 html 标记)
您提出的这个解决方案有两个类(这是因为您声明您并不总是希望将.inputbase 应用于输入元素)。
LESS 和 CSS 输出*
.inputbase {
/* your base code */
}
.someInput {
/*some input special code */
}
.someOtherInput {
/*some other input special code */
}
.andAnotherInput {
/*and another input special code */
}
这确实有最少的 CSS,但它的缺点是它还需要两个类的额外 HTML 标记,<input class="inputbase someInput" /> 等。
4.一个基类覆盖
这可能比上面的要好。
LESS 和 CSS 输出
input {
/* your base code */
}
.someInput {
/*some input special code */
/*override input base code if needed */
}
.someOtherInput {
/*some other input special code */
/*no override if not needed */
}
.andAnotherInput {
/*and another input special code */
/*no override if not needed */
}
如果大多数输入都有基本输入代码,您可以简单地在 input 元素定义中定义基本输入代码,然后只需覆盖您不需要的特殊 css 代码中的属性。这允许使用单个应用 <input class="someInput" /> 的类来减少 html。这将使 CSS 和 HTML 不那么混乱,但缺点是要记住基本代码是什么,并且可以在需要时覆盖它。
总结
最佳在很大程度上取决于您所面临的特定情况。但也许这两个额外的选项会帮助你思考你的案例。在大多数情况下,我个人会选择 #2 或 #4,但同样,也有 #1 和 #3 的应用程序。