Snake Eyes
Snake Eyes

Reputation: 16764

Use single background image for different HTML elements using CSS sprite

I want to ask you if is possible to use same background-image for different HTML elements ?

Means, I have the HTML code (a part of it):

<div class="src">
 <form action="#">
  <input type="text" class="text" />
  <input type="submit" class="submit" />
 </form>
</div>


<div class="menu">
 <ul class="level1">
  <li class="test1"><a href="#">Test1</a></li>
  <li class="test2"><a href="#">Test2</a></li>
 </ul>
</div>

and simple css

.src {
 background: url(images.png) 0 -45px no-repeat;
}

.menu ul.level1 li {
 background: url(images.png) 0 0 no-repeat;
}

.menu ul.level1 li.test1 {
 background-position:-15px -120px;
}

.menu ul.level1 li.test2 {
 background-position: -50px -120px;
}

Is this technique good ? It is occupy less HTTP requests ?

How to write in CSS a generic background image and use ,for different HTML elements, only background-position ? Or is not possible ?

Means:

.generic {
 background: url(images.png) no-repeat;
}

.src {
 background-position: 0 -45px;
}

.menu ul.level1 li {
 background-position: 0 0;
}

.menu ul.level1 li.test1 {
 background-position:-15px -120px;
}

.menu ul.level1 li.test2 {
 background-position: -50px -120px;
}

Thanks

Upvotes: 1

Views: 519

Answers (1)

Billy Moat
Billy Moat

Reputation: 21050

Yes this is perfectly fine.

You can simply declare the background image for each element that will use it like so:

.element1, .element2, .element3 {
 background-image:url(image.png);
 background-repeat:no-repeat;
}

Then declare the background position per element like you have done.

Upvotes: 1

Related Questions