Question

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');
});
Was it helpful?

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);
});

OTHER TIPS

LIVE DEMO

$('img').each(function() {
    $(this).wrap('<span class="image-wrap ' + this.className + '"/>').removeAttr('style');
    this.className='';
});

CSS:

.img1{
  width:300px;
  border:3px solid #f00;
  margin-left:40px;       /* NOTE THE IMAGE MARGIN ! */
}

.image-wrap{
  position:relative;
  display:inline-block;
  box-shadow: inset 0px 0px 20px #f00;
}

.image-wrap img{
   position:relative;
   width:100%;
   z-index:-1;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top