开发者

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

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?


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/


Support for :before and :after pseudo elements on img tags is limited, if at all existent on most browsers.

The best solution would be to place your img inside a div, and then have the class applied to the actual div, rather than the img.

You almost have the usage for the pseudo element correct. You can give this a try:

.somediv { position:relative;}

.somediv:before {
  position: absolute;
  content: '';
  height: 26px;
  width: 26px;
  top: 0;
}

.somediv.foo1:before { 
  background: url("../images/sprite.png") no-repeat -2px -2px;
  left: 0;
}

.somediv.foo2:before { 
  background: url("../images/sprite.png") no-repeat -2px -28px;
  right: 0;
}

Use the background:; property rather than the content:; property so that you can position the sprite within the :before pseudo element.

left:; right:; and top:; should be used for absolute positioning of the pseudo element relative to its parent (.somediv).

Placing a 1px border around your pseudo element will help you understand the different positioning :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜