Search code examples
htmlcssimagepositionwidth

How can I get different images to fit in the same 'box'?


How can I make sure that the images always are on the 'same' width and height, so they are matched in terms of those two? Now the second one is much larger and the boxes don't match up anymore. I need to get a big list with images that I got from someone, and they are not all the same dimensions sadly. The images need to be scaled proportionally

.slider-item {
  width: 50%;
  display:block;
  float:left;
}
.slider-item img {
  max-width: 100%;
}
.text {
  background-color: grey;
}
<div class="slider-item">
   <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/42/Shaqi_jrvej.jpg/1200px-Shaqi_jrvej.jpg" alt="product">
   <div class="text">
      <h3>123</h3>
      <h4>23</h4>
      <h2>Bonte</h2>
      <p>Text</p>
      <a href="">Order</a>
   </div>
</div>

<div class="slider-item">
   <img src="https://pi.tedcdn.com/r/talkstar-assets.s3.amazonaws.com/production/playlists/playlist_398/reconnect_with_nature.jpg" alt="product">
   <div class="text">
      <h3>123</h3>
      <h4>23</h4>
      <h2>Bonte</h2>
      <p>Text</p>
      <a href="">Order</a>
   </div>
</div>


Solution

  • Set a height and a width to the images. Then apply the object-fit: cover CSS rule on them.

    The object-fit CSS property sets how the content of a replaced element, such as an or , should be resized to fit its container.

    Possible values: contain, cover, fill, none, scale-down

    .slider-item {
      width: 50%;
      display: block;
      float: left;
    }
    
    .slider-item img {
      width: 100%;
      height: 10rem;
      object-fit: cover;
    }
    
    .text {
      background-color: grey;
    }
    <div class="slider-item">
      <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/4/42/Shaqi_jrvej.jpg/1200px-Shaqi_jrvej.jpg" alt="product">
      <div class="text">
        <h3>123</h3>
        <h4>23</h4>
        <h2>Bonte</h2>
        <p>Text</p>
        <a href="">Order</a>
      </div>
    </div>
    
    <div class="slider-item">
      <img src="https://pi.tedcdn.com/r/talkstar-assets.s3.amazonaws.com/production/playlists/playlist_398/reconnect_with_nature.jpg" alt="product">
      <div class="text">
        <h3>123</h3>
        <h4>23</h4>
        <h2>Bonte</h2>
        <p>Text</p>
        <a href="">Order</a>
      </div>
    </div>