少:最好使用继承或多个类

Max*_*lmo 34 css less

我有一个inputbase(){}类的LESS文件.我经常使用它,但不是每种输入类型.当我编译时,我在输出的CSS文件中有很多重复的样式.

我看了一下bootstrap如何使用LESS为他们的网格,他们使用相同的方法; 哪里column 1 etc会从column基类继承.这似乎再次产生了很多CSS.

我应该.inputbase .specificClass 在每个<input />人中使用而不是使用LESS继承吗?

Sco*_*ttS 82

各种选项,没有设置答案

这将取决于你的代码,你的目标等,你如何获得各种元素的样式.这里有一些可能性,每种都有优点和缺点.

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 */
}
Run Code Online (Sandbox Code Playgroud)

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 */    
}
Run Code Online (Sandbox Code Playgroud)

如果有一行或两行代码.inputbase(),并且如果它混合的不仅仅是几个实例,那么这将产生大量额外的代码.这是您遇到的问题.

2.扩展课程

似乎LESS只是准备允许扩展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 */
}
Run Code Online (Sandbox Code Playgroud)

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 */   
}
Run Code Online (Sandbox Code Playgroud)

优点是所有基本代码都不重复,但重复的是选择器,因为它们首先与基本代码组合在一起,然后再输出单个代码.如果一个人喜欢将他们的代码保存在一个选择器定义中,那么这就不可能了.否则,这提供了一种减少CSS输出的好方法.

3.两个类(你建议的额外html标记)

你提出的这个解决方案有两个类(这是因为你声明你并不总是想要.inputbase应用于输入元素).

少量和CSS输出*

.inputbase {
  /* your base code */
}

.someInput {
  /*some input special code */
}

.someOtherInput {
  /*some other input special code */
}

.andAnotherInput {
  /*and another input special code */
}
Run Code Online (Sandbox Code Playgroud)

这确实具有最少量的CSS,但它的缺点是它还需要两个类的额外HTML标记<input class="inputbase someInput" />等.

4.一个覆盖基础的类

这可能比上面更好.

较少和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 */
}
Run Code Online (Sandbox Code Playgroud)

如果大多数输入都有baseinput代码,您只需在input元素定义中定义基本输入代码,然后在特殊的css代码中覆盖您不需要的属性.这样只需要应用单个类就可以减少html <input class="someInput" />.这将使CSS和HTML不会变得混乱,但缺点是记住基本代码是什么,并且如果需要可以覆盖它.

摘要

什么是最好的取决于你面临的特殊情况.但也许这两个额外的选项将帮助您思考案例.在大多数情况下,我个人会选择#2或#4,但同样也有#1和#3的应用程序.

  • `.someInput {&:extend(.inputbase);/*一些输入特殊代码*/}`是我正在寻找的!非常感谢分享. (3认同)
  • 选项2看起来很合适.谢谢你,精彩的回答! (2认同)