Evanss
Evanss

Reputation: 23563

How to use image sprites when element is larger than the image?

If I want to use image sprites but the elements im styling are much larger than the individual icons, can this be done?

Lets say for the following I wanted to style each p with a small icon thats about the same size of the actual text. To stop the other icons in the image sprite being visible I would need a lot of white space between each one, which presumably could nullify the file size and number of http requests benefit.

http://jsfiddle.net/MFpxD/1/

p {
       background: gold;
        line-height: 6em;
}
<p>Text</p>
<p class="one">Text 2</p>
<p class="two">Text 3</p>
<p class="three">Text 4</p>

Is the only robust option to add markup? EG I could add a span to each p tag which had the image sprite applied to it, and also had a fixed height and width. However ideally id like a solution that doesnt add markup.

Upvotes: 1

Views: 188

Answers (1)

cimmanon
cimmanon

Reputation: 68319

You can use the :before/:after pseudo elements to contain your sprite:

http://cssdeck.com/labs/g99y1q0b

p:before {
  content: '';
  display: inline-block;
  background: url('http://placekitten.com/100/100') no-repeat;
  width: 50px;
  height: 50px;
}

Upvotes: 2

Related Questions