Hummingbird
Hummingbird

Reputation: 3

CSS how to deal with a lot of sprite without having to create a new css class

I have a list of image (around 30) and I want to create CSS sprite so that they are colored when hovered. The images all have the same size. The problem is that if I just want to have one css class, I have to put the background-image on the inline html like this :

CSS:

.sprite{
    background-position: 0 0;
    width: 185px;
    height: 100px;
}

.sprite:hover{
    background-position: 185px 0;
}

HTML:

<div class="sprite" style="background: url('image1');">
<div class="sprite" style="background: url('image2');">
<div class="sprite" style="background: url('image3');">
...

And it does not work. I only manage to do the sprite if I put the background image on the css but if I do this, I would have to create as many CSS classes as I have images which is not elegant at all. Do you have a better idea? (PS: I'm using Less CSS)

Upvotes: 0

Views: 76

Answers (2)

fast
fast

Reputation: 885

The Problem is that you overwrite all background attributes inline (incl. -position); use:

style="background-image: url('image1');"

Upvotes: 0

Ties
Ties

Reputation: 5846

Often sprites are used for icons, then people would create one .icon class and 'extend' it by another class like .icon.facebook. The .icon class contains all the dimensions and other default settings for the icon. The extended class does the customization of the icon.

.icon {
  width: ...;
  height: ...;
  display: inline-block;
  background: transparent url(...) no-repeat;
}
.icon.facebook {
  background-position: ...px ...px;
}
.icon.facebook:hover {
  // color version
  background-position: ...px ...px;
}

Upvotes: 1

Related Questions