Cain Nuke
Cain Nuke

Reputation: 3089

How to show only part of an image as the background

Hi,

I have this code:

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;
}

The thing is that the image I am using for the background contains many sprites so I just want to show the one on coordinates 0 -100px. However, since the label width may vary (because of the length of the contained text) it will show also the sprites next to the one I need.

How can I solve this without editing the image? I want to show only 25x25px of the background image. The rest I dont need. Height I can define but width I cant because as I already said, it must fit the text in the label.

Thank you.

    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>

Upvotes: 0

Views: 5859

Answers (2)

Your problem: Don't tightly couple it (don't apply background on label), instead create a new span for that image. This will also help keep your code clean

.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>

Upvotes: 0

Shaggy
Shaggy

Reputation: 6796

Instead of applying the background directly on the label, create a pseudo element, size it to the dimensions of the image in your sprite and apply your background to it instead.

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>

Upvotes: 3

Related Questions