Note that this answer works and explains why it works for infinite height CSS grid. In my case, the height is limited (which could be 100vh
or due to flex-grow
but it’s not infinite).
Let’s say I have a certain space for a grid (decided by a flex box which is the remaining space of whatever remaining of the screen). I want it to be divided into two equal rows. The top one should be an img
with object-fit: scale-down
that take up all 50% height and at most 100% width and the bottom row should be some random text. Problem is, when the img
is bigger, it takes up additional space (see example below).
Is it possible to divide a CSS grid or flex box (or any kind of display) into two strictly equal rows?
body {
height: 100vh;
width: 500px;
display: flex;
margin: 0;
padding: 0;
}
.grid {
height: 100%;
width: 100%;
display: grid;
grid-template-rows: 1fr 1fr;
background-color: cornflowerblue;
padding: 1rem;
}
img {
display: block;
width: 100%;
height: 100%;
object-fit: scale-down;
}
.content {
background-color: black;
color: white;
}
<div class="grid">
<img src="https://placehold.co/600x400" />
<div class="content">Another content</div>
</div>
2
Answers
In this approach, I used a flexbox container with the class
.flex
to split a space into two equal rows. The top row holds an image withobject-fit: scale-down
, while the bottom row contains text. To prevent the image from affecting the row’s height, I setflex-grow: 1
and a fixedheight: 50%
for the image. The text row’s height is also set to50%
withflex-grow: 1
. This layout maintains equal row heights even when the image is larger.If you put the
img
inside adiv
and set theimg
position: absolute
, the setting seems to work OK.