无法将背景大小设置与背景图像分离?

时间:2016-12-20 17:53:13

标签: html css css3

尝试减小CSS文件的大小,我想分解一些命令,例如background-size。假设我有很多这样的部分:

#interlude {
  background: url(https://.../unsplash.jpg) no-repeat center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

使用中:

<div id="interlude"></div>

如果我有许多不同的“interlude”div,CSS中所有与大小相关的行都是重复的。我想得到类似的东西:

#interlude {
  background: url(https://.../unsplash.jpg) no-repeat center fixed;
}
.bw-back-cover {
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

在这种情况下,bw-back-cover类只声明一次。但它不起作用,我不知道这是一种正常的行为。

Codepen

上的两个案例

1 个答案:

答案 0 :(得分:3)

对于CodePen,简写background属性会覆盖所有与背景相关的属性,而不仅仅是指定的属性 - 因此background-size被忽略,因为{ {1}}具有更高的优先级(在ID与类之间)。

有两种方法可以解决这个问题。

1)简单的方法是将background添加到!important属性的每一行,这样它们就不会被background-size简写覆盖。 (但是,我建议下面的第二个解决方案,因为background很难在需要时覆盖。)代码:

!important

2)更清洁的修复方法是拆分背景属性而不是使用速记,因此.bw-back-cover { -webkit-background-size: cover !important; -moz-background-size: cover !important; -o-background-size: cover !important; background-size: cover !important; } 不会被覆盖。代码:

background-size