如何用精灵设置背景位置?

时间:2017-01-01 16:53:11

标签: html css css-sprites css-specificity

您好,新年快乐:D所以这是一个问题:我想在页面上显示6个带有精灵的热气球。实际精灵包含6个彩色气球。让我们看看代码和结果。

HTML:

<div class="hotairballoons">
    <div class="ball-1"></div>
    <div class="ball-2"></div>
    <div class="ball-3"></div>
    <div class="ball-4"></div>
    <div class="ball-5"></div>
    <div class="ball-6"></div>
</div>

CSS:

.hotairballoons > div[class^="ball-"] {
    background: url(../img/sprites.png);
    background-repeat: no-repeat;
    width: 69px;
    height: 110px;
}

.ball-1 {
    background-position: 0px 0px;
}

.ball-2 {
    background-position: -69px 0px;
}

.ball-3 {
    background-position: -138px 0px;
}

.ball-4 {
    background-position: 0px -110px;
}

.ball-5 {
    background-position: -69px -110px;
}

.ball-6 {
    background-position: -138px -110px;
}

结果:

enter image description here

开发者控制台中显示的内容:

enter image description here

为什么要越过?我做错了什么?

2 个答案:

答案 0 :(得分:0)

你需要纠正两种风格。

CSS特异性

选择器.hotairballoons > div[class^="ball-"]得分0 2 1。选择器.ball-1得分为0 1 0。得分较高的相同规则会覆盖较低的规则。您可以使用此工具CSS Explain来检查。

CSS简写规则

属性background是一种速记规则,background-position是其中的一部分,初始值为0% 0%

规则.hotairballoons > div[class^="ball-"] {background:...;}会覆盖.ball-1 {background-position:...;}

要更正这一点,您可以将background声明为单独的规则,以便它们不会被覆盖。

.hotairballoons > div[class^="ball-"] {
    background-image: url(../img/sprites.png);
    background-repeat: no-repeat;
}

然后保持background-position未设置,然后像你一样在每个单独的类中设置它。

.ball-1 {
    background-position: 0px 0px;
}
.ball-2 {
    background-position: -69px 0px;
}

答案 1 :(得分:-2)

工作正常。

但如果您想更正控制台,则应在每个!important的末尾添加background-position