CSS background image on top of <img>

Here's what I did for my solution. Essentially, I'm using the "IMG" as a placeholder. So that my Background image maintains the correct proportions as the browser resizes.

.image-overlay {
  background-image: url("insert image here");
  display: inline-block;
  position: relative;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: center;
}
.image-overlay img {
  opacity: 0;
}

HTML

<div class="category-overlay">
    <img src="/images/placeholder.jpg" alt="">
</div>

Another way, is to set content to empty and set a background, for example:

img {
    background: url(...) center center no-repeat;
    background-size: cover;
    content: '';
    display: block;
    width: 800px;
    height: 100px;
}

Here is a demo: http://jsfiddle.net/infous/effmea8x/

In this demo the first image is standard but with unproportional width and hight, the second one is with the background. The first one is scaled badly, the second one is OK.


You could use a pseudo-element. In this example, the :after pseudo element is absolutely positioned relative to the parent element. It takes the dimensions of the entire parent element, and the size of the parent element is determined by the size of the child img element.

.test {
  display: inline-block;
  position: relative;
}
.test:after {
  content: '';
  position: absolute;
  top: 0; right: 0;
  bottom: 0; left: 0;
  background: url(http://placehold.it/20x20/1) repeat;
}
<div class="test">
    <img src="http://lorempixel.com/200/200">
</div>

As a side note, your example wasn't working for a couple of reasons. The parent element has a background image, but since the child element establishs a stacking context within the parent element, it's not possible for the parent's background image to appear above the child img element (unless you were to completely hide the img element). This is why the z-indexs weren't working as expected.

In addition, the img element was absolutely positioned. In doing so, it is removed from the normal flow, and since it was the only child element, the parent element therefore collapses upon itself and it doesn't have any dimensions. Thus, the background image doesn't show up. To work around this, you would either have to set explicit dimensions on the parent element (height/width), or you could remove the absolute positioning on the child img element.

Tags:

Html

Css