Issue
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.
.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>
Solution
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>
Answered By - Qiu Zhou
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.