I created a very simple flexbox layout, I have two rows and 5 columns. My idea is to put pictures in the boxes, but when I add an image it distorts the grid.
My code looks like:
<div id="head">
<div class="row">
<div><img src="https://cdn.britannica.com/98/214598-050-9879F2FA/giant-sequoia-tree-Sequoia-National-Park-California.jpg" /></div>
<div><!-- --></div>
<div><!-- --></div>
<div><!-- --></div>
<div><!-- --></div>
</div>
<div class="row">
<div><!-- --></div>
<div><!-- --></div>
<div><!-- --></div>
<div><!-- --></div>
<div><!-- --></div>
</div>
</div>
My css looks like:
body {
margin: 0;
}
#head .row {
display: flex;
}
#head .row div {
background: #ddd;
flex: 1 0 auto;
height: auto;
margin: 1px;
}
#head .row div::before {
content: '';
float: left;
padding-top: 100%;
}
#head img {
height: 100%;
object-fit: contain;
width: 100%;
}
When I add an image into the mix with object-fit: contain or cover, nothing seems to happen. My expectation is that it would fit inside my box.
Does anyone know what I could adjust to fix this?
Fiddle without the image: https://jsfiddle.net/joshrodgers/c7j48zw1/1/
Fiddle with the image: https://jsfiddle.net/joshrodgers/ro16atsg/
I read that adding the 100% to the width and height would help my object-fit because then I’m making the image the same size as the container…but that doesn’t seem to change the size of the image at all.
Any help is appreciated 🙂
Thanks,
Josh
2
Answers
I assume it’s not working because your boxes don’t have an explicit size. (They’re just being pushed open by the
before
pseudo-element, but the image then just pushes them further open.) I’m not sure if you’re using:before
just to give the boxes visual dimensions, but there may be better approaches with Flexbox, such as this:You can get those nice square boxes with
aspect-ratio
, but there are other ways to do it, of course.If you want the layout to be a grid, use a CSS grid.