Search code examples
csslessmaskpseudo-elementimage-masking

CSS - Using a pseudo-element for an image mask


I'm showing an image on a page and I wish to add a mask to achieve a specific border-and-corner effect.

To do this I was hoping to use a pseudo-element in the following manner:

img
{
    height: 58px;
    left: 0;
    position: absolute;
    top: 0;
    width: 58px;
    z-index: 1;

    &:after
    {
        background-image: url(images/frame.gif);
        content: " ";
        height: 58px;
        left: 0;
        position: absolute;
        top: 0;
        width: 58px;
        z-index: 2;
    }
}

But the mask image never shows up. I've also tried adding a negative left- and top-margin to 'pull' the pseudo-element back over the <img> but still nothing.

Is there a glaring error in my CSS or does the problem lie with an inherent limit to pseudo-elements?


Solution

  • By default the img tag is an inline element and it is not a container to add an after pseudo class. I'll suggest the following code:

    div.container {
        img {
            display: block;
            height: 58px;
            left: 0;
            position: absolute;
            top: 0;
            width: 58px;
            z-index: 1;
        }
        &:after {
            display: block;
            background-image: url(images/frame.gif);
            content: " ";
            height: 58px;
            left: 0;
            position: absolute;
            top: 0;
            width: 58px;
            z-index: 2;
        }
    }
    

    Notice that the pseudo class is also a block element.