CSS: using image sprites with css pseudo classes :before and :after

matt picture matt · Aug 15, 2011 · Viewed 24.8k times · Source

I have never tried that before. I created an image sprite that is contains two icons. Each icon is 26px wide and high. So the sprite is 26x52px.

I have an element that is either in a div.something or in a div.anything. Depending on which class it's in I want to add a corner cap to the left or right.

So therefore I'm positioning the .element relative, the apply the :before pseudoclass to the img and position it absolute with a height and width of 26px so only one icon of the sprite fits in. I also apply "overflow:hidden" in order to hide the second icon on the sprite.

.element {
    position:relative;
}

.element:before{
    content: url("../images/sprite.png");
    position: absolute;
    height:26px;
    width:26px;
    overflow:hidden;
}

.something .element:before {
    top: -2px;
    left: -2px;
}

anything .element:before {
    top: -28px;
    right: -2px;
}

This works fine for the left-corner where I use the first top icon in the sprite. However now I wonder how I can show only the second icon in the sprite for the "anything .element".

So actually the "mask" should be positioned at -2px, -2px but the sprite img inside should start at -26px so the second icon is shown.

Is this possible with css the way I'm doing it right now?

Answer

Tatu Ulmanen picture Tatu Ulmanen · Aug 15, 2011

Don't use content to insert your image, as you cannot modify its position. Instead, set the content to " " and add the sprite as a background image. You can then use the background-position property to move the sprite to the correct position. Otherwise your example should be working just fine.

A working demo:

http://jsfiddle.net/RvRxY/1/