将背景图像属性合并到单个CSS规则中但不指定背景颜色?

时间:2014-05-14 08:53:43

标签: css

我希望带有类的元素始终具有相同的背景颜色。根据天气情况,它有一个额外的类,它的背景图像将会改变。

这样可以正常工作,但是对于不同的背景属性必须有单独的规则有点混乱:

.class { 
  background-color: grey;
  background-image: url("image1.jpg");
  background-repeat: no-repeat;
  background-position: right center;
}

.class.additional { 
  background-image:  url("image2.jpg"); 
}

这有效,但我不得不重复“灰色”'这不是长期维护代码的理想选择:

.class {
  background: grey url("image1.jpg") no-repeat right center;
}

.class.additional {
  background: grey url("image2.jpg") no-repeat right center;
}

有没有办法在一行上写下所有背景属性,但不重复两种样式的背景颜色?

1 个答案:

答案 0 :(得分:1)

您可以在第一个规则中指定速记,并在第二个规则中仅覆盖background-image

.class { 
  background: grey url("image1.jpg") no-repeat right center;
}

.class.additional { 
  background-image: url("image2.jpg"); 
}