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?
The ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.
An image sprite is a collection of images put into a single image. A web page with many images can take a long time to load and generates multiple server requests. Using image sprites will reduce the number of server requests and save bandwidth.
::before (:before) In CSS, ::before creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With