2016-09-07 99 views
0

喜的只是一部分,如何显示的图像为背景

我有这样的代码:

input[type="checkbox"]:not(old) + label { 
    background: url("sprites.gif") no-repeat -220px -54px; 
    box-sizing: border-box; 
    height: 25px; 
    padding: 0 0 0 35px; 
} 

的事情是,我使用的背景图像中包含许多精灵,所以我只是想要在坐标0 -100px上显示。但是,由于标签宽度可能会有所不同(因为包含文本的长度),它还会显示我需要的精灵旁边的精灵。

如何在不编辑图像的情况下解决此问题?我只想显示25x25像素的背景图像。剩下的我不需要。身高我可以定义,但我不能宽度,因为正如我已经说过,它必须符合标签中的文字。

谢谢。

input[type="checkbox"]:not(old) + label { 
 
     background: url(http://cdn.sstatic.net/Sites/stackoverflow/../../img/share-sprite-new.svg?v=78be252218f3) no-repeat -220px -54px; 
 
     box-sizing: border-box; 
 
     height: 25px; 
 
     padding: 0 0 0 35px; 
 
    }
<input type="checkbox"><label>Some randome text</label>

+0

你能提供一个链接到一个原型 – Terabyte

+0

片段加入到这个问题。 –

回答

1

而不是直接在label应用background,创建一个伪元素,它的大小与图像的在你的精灵的尺寸和改为使用您的background

input[type="checkbox"]:not(old)+label{ 
 
    box-sizing:border-box; 
 
    height:25px; 
 
} 
 
input[type="checkbox"]:not(old)+label::before{ 
 
    background: url(http://cdn.sstatic.net/Sites/stackoverflow/../../img/share-sprite-new.svg?v=78be252218f3) no-repeat -220px -54px; 
 
    content:""; 
 
    display:inline-block; 
 
    margin-right:10px; 
 
    height:25px; 
 
    vertical-align:bottom; 
 
    width:25px; 
 
}
<input type="checkbox"><label>Some random text</label>

+0

这是我最后的手段,我不想使用它,但似乎是唯一的方法。谢谢。 –

+0

如果这已经回答了您的问题,请考虑接受:) – Shaggy

0

您的问题:不要紧密结合它(不适用标签上的背景),而不是创建该图像的新跨越。这也将有助于保持你的代码干净

.sprite { 
 
    display: inline-block; 
 
    background: 
 
url(http://cdn.sstatic.net/Sites/stackoverflow/../../img/share-sprite-new.svg?v=78be252218f3) no-repeat -225px -50px; 
 
    height: 25px; 
 
    width: 25px; 
 
}
<input type="checkbox"><span class="sprite"></span><label>Some randome text</label>

+0

谢谢,但如果你看看我的问题的代码,你会看到我已经知道背景位置,因为我正在使用它。问题不在于此。问题是精灵只有25px宽,左侧有更多的精灵,所以如果容器(在这种情况下是标签)宽于25px,那么左边的精灵将显示。 –

+0

设置高度和宽度为25px和25px;使用X和Y值决定哪个部分完成! _看看我编辑的答案_ –

+0

请再次阅读我的问题。我不能将宽度设置为25px,因为那么标签WONT FIT内的文字。看看我刚编辑的代码片段。 –