Search code examples
htmlcssimagecentering

best fit img with caption into element


Building an image slideshow, I have a container div of arbitrary size and aspect ratio into which I have to best fit an image, centred, with a caption overlayed at the bottom of the image and fitting its width. My best solution to date is to contain the image and the caption in a child element of the container but I'm having trouble centring it. This should be such a simple thing that I can't believe it's not staring me in the face but I can't see it. The code below uses a portrait format image but I need it to handle landscape also. I'm using React so jQuery is out.

.container {
  position: relative;
  width: 80%;
  height: 48vw;
  /* 4:3 */
  margin: 0 auto;
  display: flex;
  justify-content: center;
}

.img-wrap {
  background-color: #efe;
}

img {
  position: absolute;
  max-width: 100%;
  max-height: 100%;
}

.caption {
  position: absolute;
  bottom: 0;
  color: #fff;
  background-color: rgba(153, 153, 153, 0.541)
}
<div class="container">
  <div class="img-wrap">
    <img src="https://png.pngtree.com/thumb_back/fw800/background/20190223/ourmid/pngtree-full-aesthetic-aurora-night-sky-background-skystarry-skystarnight-viewbackgroundstar-image_87582.jpg" height="1600px">
    <div class="caption">Caption Content</div>
  </div>
</div>


Solution

  • Update your code like below:

    .container {
      width: 80%;
      height: 48vw;
      /* 4:3 */
      margin: 5px auto;
      text-align: center;
    }
    
    .img-wrap {
      background-color: #efe;
      height: 100%;
      display: inline-block;
      position: relative;
    }
    
    img {
      max-width: 100%;
      height: 100%;
      display: block;
      object-fit: contain; /*or cover if you want to cover all the area*/
      object-position: bottom;
    }
    
    .caption {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      color: #fff;
      background-color: rgba(153, 153, 153, 0.541)
    }
    <div class="container">
      <div class="img-wrap">
        <img src="https://i.picsum.photos/id/10/400/600.jpg">
        <div class="caption">Caption Content</div>
      </div>
    </div>
    
    <div class="container">
      <div class="img-wrap">
        <img src="https://i.picsum.photos/id/10/600/300.jpg">
        <div class="caption">Caption Content</div>
      </div>
    </div>