CSS background image on top of

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.

Leave a Comment