Christian Luneborg
Christian Luneborg

Reputation: 511

Hide <img src> and display background image on top not working

I have a problem hiding the <img src="/"> and overlay the background image on a media 480px version.

I tried to use the code based on CSS background image on top of <img> and it doesn't work for me.

JDFIDDLE

HTML

<div class="j_img-overlay">
    <img src="https://image.flaticon.com/teams/slug/freepik.jpg">
</div>

CSS

.j_img-overlay {
   width: 100px;
   height: 100px;
}

.j_img-overlay img {
   background-size: auto;
   background: url(http://icons.iconarchive.com/icons/graphicloads/100-flat/256/home-icon.png) no-repeat;
   position: relative;
   box-sizing: border-box;
   width: 100px;
   max-width: 100px;
   z-index: 100;
   }

Upvotes: 2

Views: 2609

Answers (1)

Zeev Katz
Zeev Katz

Reputation: 2273

First of all <img/> element should not display background-image. Additionally, only background property let you adjust all of the available background style options at once so, unfortunately background-image can takes only image urls and not repeating value.

Find here more about Background Image and Background css properties.


To make the overlay works properly you can using pseudo element (after, before) with absolute positioning to fill the container of the image element. Relative position is required for the container to avoid leakage of the pseudo element (with the absolute position that we defined).

Find here more about Pseudo Elements - CSS.

Working example:

.j_img-overlay {
  position: relative;
  width: 100px;
}
.j_img-overlay::after {
  content: "";
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url(http://icons.iconarchive.com/icons/graphicloads/100-flat/256/home-icon.png) no-repeat;
  background-size: cover;
}

.j_img-overlay img {
  display: block;
  width: 100%;
}
<div class="j_img-overlay">
  <img src="https://image.flaticon.com/teams/slug/freepik.jpg">
</div>

Upvotes: 2

Related Questions