Search code examples
jquerycssinsets

keep (or set) box-shadow inset for image


I would like to set a box-shadow inset for images. This is not possible for images, so I googled for workarounds and found this as one of them: JsFiddle

The problem is that the span has a good wrap on the image, but if the image has a styling which include margin or padding then the span doesn't fit on the image as you can see in the example.

So what can I do to make the span always wrap the image without the white space of the margin? If there is a better way of doing this please let me know.

CSS

.image-wrap {
    position: relative;
    display: inline-block;
    max-width: 100%;
    vertical-align: bottom;
}
.image-wrap:after {
    content: ' ';
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0px;
    left: 0px;
        box-shadow: inset 0px 0px 0px 5px red;
}

.image-wrap img {   
    width:300px;
    margin-left:150px;
}

Jquery

$('img').each(function() {
    var imgClass = $(this).attr('class');
    $(this).wrap('<span class="image-wrap ' + imgClass + '" style="width: auto; height: auto;"/>');
    $(this).removeAttr('class');
});

Solution

  • One approach that works in this specific case would be to manually move the margin-left from the img to the parent span:

    $('img').each(function () {
        var imgClass = $(this).attr('class');
        $(this).wrap('<span class="image-wrap ' + imgClass + '" style="width: auto; height: auto;"/>').removeClass(imgClass)
            .parent().css('margin-left',$(this).css('margin-left')).end()
            .css('margin-left',0);
    });