有没有办法重用/压缩CSS,使其更小,更清洁?

时间:2011-06-01 12:29:35

标签: css optimization css-selectors

我在外部CSS文件中有以下样式。

.callButton {
  width: 100px;
  height: 25px;
  float: right;
  /* other styles here */
  background-img: url('images/callButton.png');
}

.otherButton {
  width: 100px;
  height: 25px;
  float: right;
  /* same styles from callButton here */
  background-img: url('images/otherButton.png');
}

/* 5 more similar buttons */

正如您所看到的,只有属性background-img不同,但我要为每个属性使用不同的类。有没有什么方法可以为公共属性使用相同的类,为background-img属性使用不同的(如变量)?

5 个答案:

答案 0 :(得分:6)

你会想要这样的东西,其中包括:

.button {
    width: 100px;
    height: 25px;
    float: right;
}

.callButton {
    background-img: url('images/callButton.png');
}

.otherButton {
    background-img: url('images/otherButton.png');
}

然后,将您的HTML更改为:

<span class="button otherButton"></span>

答案 1 :(得分:0)

您可以使用以下内容进行简化:

.callButton, .otherButton, ...other buttons... {
    width: 100px;
    height: 25px;
    float: right;
}

.callButton {
    background-img: url('images/callButton.png');
}

.otherButton {
    background-img: url('images/otherButton.png');
}

答案 2 :(得分:0)

制作级联,级联

.callButton, .otherButton 
{
   width: 100px;
   height: 25px;
   float: right;
  }  
.callButton {
   background-img: url('images/callButton.png');
 }  
.otherButton {
   background-img: url('images/otherButton.png'); 
}

使用多个选择器可以获得相同的效果,但使您的风格更易于阅读,一致并且只允许分离“不同”部分。

注意:类别符号的逗号分隔在第一行上显示“适用于其中每一个”。

答案 3 :(得分:0)

显而易见的答案是将所有相关元素赋予同一个类。即使您因其他原因需要保留现有的类名,这也会有效,因为您可以指定多个类。

.allButtons {
  width: 100px;
  height: 25px;
  /* etc */
}

.callButton {
  background-img: url('images/callButton.png');
}

使用这样的HTML:

<div class='allButtons callButton'>Call</div>
<div class='allButtons otherButton'>Other</div>
etc...

(顺便说一下,如果'callButton'是唯一的,你也可以使用它作为ID而不是类;它会更有意义。但它也可以作为一个类工作得很好)

如果您不想这样做(例如,您无法更改HTML),那么您可以使用逗号指定CSS中所有类的一组样式:

.callButton, otherButton, yetanotherButton, etc {
  width: 100px;
  height: 25px;
  float: right;
  /* other styles here */
}

.callButton {
  background-img: url('images/callButton.png');
}

最后,虽然在这种情况下上面的解决方案对你来说没问题,但如果你想编写更多一般的样式表,你可能还想查找像LESS这样的产品,这些产品扩展了CSS的语法使其更容易使用。然后,在部署到您的站点之前,您必须将其转换为普通的CSS,但出于开发目的,它是一个简洁的小工具。

答案 4 :(得分:0)

具有相同CSS规则的所有按钮将放在一起

 .button1, .button2, .button3, .button4, .button5 {width: 100px; 
 height: 25px; float: right; /* other styles here */}  

然后每个按钮都可以收到自己的background或其他特定样式:

 .button1 {background-img: url('images/callButton.png';) 
 etc.

通过这种方式,您的HTML无需在相关div上设置多个班级。

相关问题