2

How can I set my images' height to be the same as its' width?

The height of the images will always need to be the same size as its' width, even when the width of the images changes due to resizing of the browser window.

To explain further, if the width of the images are 500px, then its' height will also need to be 500px. If the window resizes and the width of the images changes to 600px then its' height will also need to change to 600px.

Constraints: Please don't set a fixed width on the grid or images.

Desired Result

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

img {
  width: 100%;
  object-fit: cover;  
}
<div class="grid">
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-1.jpg"/>     
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-2.jpg"/>
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-3.jpg"/>
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-4.jpg"/>
</div>
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57

2 Answers2

2

Add a div as a container for every image, set the height to 0, and padding-bottom to 100% as a percentage of it's own width:

    .grid {
      display: grid;
      grid-template-columns: 1fr 1fr;
    }

    .grid div{
      width: 100%;
      height: 0;
      padding-bottom: 100%;
      position: relative;
    }

    img {
      position: absolute;
      width: 100%;
      height: 100%;
      object-fit: cover;  
    }
 
    <div class="grid">
      <div>
        <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-1.jpg"/>     
      </div>
      <div>
        <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-2.jpg"/>     
      </div>
      <div>
        <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-3.jpg"/>     
      </div>
      <div>
        <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-4.jpg"/>     
      </div>
    </div>
 
Qiu Zhou
  • 1,235
  • 8
  • 12
1

You can just add align-self: stretch to your img css rule, like so:

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

img {
  width: 100%;
  object-fit: cover;
  align-self: stretch;
}
<div class="grid">
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-1.jpg"/>     
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-2.jpg"/>
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-3.jpg"/>
  <img src="https://vietadang.github.io/the-stars/dist/images/menu/dessert-4.jpg"/>
</div>
Mers
  • 736
  • 4
  • 12
  • You can look into minmax() css function. – Mers Sep 07 '20 at 03:24
  • @DotV , can you clarify if you are just wanting to change the img's size or an grid area that the image resides in? Changing image's width and height to the same size without cropping parts of the image is beyond CSS. – Mers Sep 07 '20 at 03:32