Search code examples
cssimagecontainersresize

auto-resize a 'div' container to fit the image?


In a div I want to have a background image and a title. The title must be centered hrz and vert in the div, this is quite easy with display: flex. But for this I need the container (the div) fit to the image that will change periodically. So the opposite question to the usual image to fit a container.


Solution

  • Is this what you are looking for?

    1. Add image to container
    2. Set a mask with absolute position that covers the whole container
    3. Set the title with flex inside that mask
    4. The title will still be centered event with images that have different dimensions

    let currentIndexTitle = 1;
    const img = document.querySelector('.myImage');
    const title = document.querySelector('.title');
    const titles = ['Title one', 'title Two', 'Title three'];
    const images = [ 'http://picsum.photos/300/300', 'http://picsum.photos/250/350', 'http://picsum.photos/250/250' ];
    
    setInterval(() => {
      const titleSelected = titles[currentIndexTitle];
      img.setAttribute('src', images[currentIndexTitle]);
      title.innerText = titleSelected;
      currentIndexTitle = (currentIndexTitle + 1) % titles.length;
    }, 5000);
    #container {
      position: relative;
      display: inline-block;
    }
    .mask {
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(0,0,0,0.8);
    }
    .mask .title {
      color: #FFF;
      font-weight: bold;
    }
    <div id="container">
      <img class="myImage" src="http://picsum.photos/400/500"/>
      <div class="mask">
        <div class="title">Title one</div>
      </div>
    </div>