开发者

Add image on top of another based on CSS class

I have a bunch of img tags on one of the pages in my site. I want to be able to add a custom image on top of a few of these images based on the css class applied to them

So in case of the statements below

<img src="image_path"/>
<img class="newclass" src="image_path"/>

I want another image added on top of the 2nd image and nothing on the first image.

Can I do this using CSS?

Thanks.

Why I want to do it this way

I can do this using 2 img tags. But it would be easier for me to make changes and add more images by just adding a class name to the img tag r开发者_如何学JAVAather than adding another img tag itself in the future.


No, you can't do it in pure CSS with just a single img element.

:after is what you would use, but that doesn't work for img elements:

Note. This specification does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.


You could do it by adding a containing element, and using :after on that.

It works "everywhere" http://caniuse.com/#feat=css-gencontent - with the exception of IE7.

For whatever reason, this specific usage of :after also doesn't work in IE8. It finally works in IE9.

http://jsfiddle.net/AQHnA/

<div class="newclass"><img src="http://dummyimage.com/100x100/ccc/fff" /></div>

.newclass {
    position: relative;
    float: left
}
.newclass img {
    display: block
}
.newclass:after {
    background: url(http://dummyimage.com/32x32/f0f/fff);
    width: 32px;
    height: 32px;
    display: block;
    content: ' ';
    position: absolute;
    bottom: 0;
    right: 0
}


It's best to have a parent element for your image. This is how you can do it with links (or any other element):

.newclass {
    background:url(2.jpg) no-repeat;
    display:inline-block
}
.newclass img {
    position:relative;
    z-index:-1
}

<a href="#"><img src="1.jpg" /></a>
<a class="newclass" href="#"><img src="1.jpg" /></a>

This works fine in IE5.5, IE6, IE7, IE8 and Safari 5 (browsers that I tested).

Edit: thirtydot noticed that this doesn't work if you have a parent container with a background color (because of the z-index on the images). See comments.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜