Add image on top of another based on CSS class

后端 未结 2 815
天涯浪人
天涯浪人 2020-12-22 12:39

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

相关标签:
2条回答
  • 2020-12-22 13:13

    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
    }
    
    0 讨论(0)
  • 2020-12-22 13:18

    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 讨论(0)
提交回复
热议问题