Search code examples
htmlcssflexboxbackground-image

Make background image to fit in flex container


I have used flexbox to create a grid which allows 3 images be aligned side by side. I have given them a width of 33.333% so they fit exactly.

However now I want to introduce a css hover effect where another image fades in when you hover over an image.

I have the effect working fine, however the issue I am having is that the image which fades in on hover is too big and as a result only about 75% of it appears in the container.

I got the code for the fade effect here, but although I have been manipulating the code I can't get the image to fit exactly 100% in the container. Both images are the exact same dimensions.

.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  flex: 1
}

.bord {
  padding: 0;
  margin: 0;
  -webkit-box-sizing: border-box;
}

.crossfd {
  background: url("https://picsum.photos/200/200?image=0");
  display: inline-block;
  background-size: cover;
}

.crossfd img {
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.crossfd img:hover {
  opacity: 0;
}
<div class="container">
  <div class="box bord crossfd">
    <img src="https://picsum.photos/200/300?image=1" width="100%" alt="Lou" />
  </div>
  <div class="box bord crossfd">
    <img src="https://picsum.photos/200/300?image=2" width="100%" alt="Lou" />
  </div>
  <div class="box bord crossfd">
    <img src="https://picsum.photos/200/300?image=3" width="100%" alt="Lou" />
  </div>
</div>


Solution

  • Try adding background-size: cover; on .crossfd class.

    You may also try contain or 100%, read the spec on MDN.

    The background-size CSS property specifies the size of the background images. The size of the image can be fully constrained or only partially in order to preserve its intrinsic ratio.