I have a question about CSS Grid. I remember not being able to get my grid to work when I tried using an img as one of the grid items, but as soon as I wrapped it in a div and manipulated the div instead, it worked. Does anybody know why this is the case? I think it has something to do with needing the grid item to be a grouping element like a div, section, footer etc.
CodePudding user response:
I don't think there should be any issue using img
without a Div
.
.grid-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(2, 1fr);
gap: 10px 10px;
grid-auto-flow: row;
width: 620px;
border:4px solid gray;
}
.grid-container>img {
width: 200px;
}
<div >
<img src="https://images.unsplash.com/photo-1664172518567-0024c1c366dc?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw4fHx8ZW58MHx8fHw=&auto=format&fit=crop&w=500&q=60" alt="">
<img src="https://images.unsplash.com/photo-1664136141640-1e0aae3fe6ec?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxMHx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60" alt="">
<img src="https://images.unsplash.com/photo-1664136262345-daa7e71f0c0b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHw5fHx8ZW58MHx8fHw=&auto=format&fit=crop&w=500&q=60" alt="">
<img src="https://images.unsplash.com/photo-1664176062054-715f89b1974b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxlZGl0b3JpYWwtZmVlZHwxNHx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60" alt="">
<img src="https://images.unsplash.com/photo-1659535867362-f3ed3d7b5513?ixlib=rb-1.2.1&ixid=MnwxMjA3fDF8MHxlZGl0b3JpYWwtZmVlZHwyMXx8fGVufDB8fHx8&auto=format&fit=crop&w=500&q=60" alt="">
</div>
CodePudding user response:
Most probably it has to do with the fact that img
element has default display
value of inline
. If you change it to block I don't think there should be any problems.
<div >
<img src="...">
<img src="...">
...
</div>
and in CSS
.my-image-class {
display: block;
...rest of css
}