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

Viewed 111

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>

2 Answers

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>
 

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>

Related