I have a grid layout defined using CSS Grid, and I want to achieve a specific layout with designated heights for certain areas. The desired grid layout looks like this:
A B C
A D E
F G E
I want the height of the area A
to be 96px and the height of the area E
to be 48px. All other areas should adjust their height automatically (auto
).
Here’s the CSS and HTML I am currently using:
<div class="table">
<div class="a">a</div>
<div class="b">b</div>
<div class="c">c</div>
<div class="d">d</div>
<div class="e">e</div>
<div class="f">f</div>
<div class="g">g</div>
</div>
.table {
display: grid;
grid-template-columns: 96px 1fr 48px;
grid-template-rows: auto auto auto;
grid-template-areas:
"a b c"
"a d e"
"f g e";
gap: 5px;
}
.table > div {
border: 1px solid black;
}
.a {
grid-area: a;
height: 96px;
}
.b {
grid-area: b;
}
.c {
grid-area: c;
}
.d {
grid-area: d;
}
.e {
grid-area: e;
height: 48px;
}
.f {
grid-area: f;
}
.g {
grid-area: g;
}
When I set the height for the A
and E
areas, the layout becomes misaligned. It seems that setting the height directly on a grid cell causes the entire layout to behave unexpectedly.
How can I set the height for specific grid areas (A
and E
) while keeping the layout intact and allowing other areas to adjust their height automatically?
4
Answers
I think you need to modify the grid definition and avoid directly setting heights on grid items.
Try this:
Hope that helps 🙂
I recommend always starting your css code with
Also you need to set
grid-template-rows: auto 48px auto;
that.e
is not go outside the grid:To achieve the desired grid layout with specific heights for certain areas while keeping the layout intact, it’s better to control the row heights through the
grid-template-rows
property rather than setting heights directly on the individual grid items. Here’s how you can modify your CSS:grid-template-rows
.Here’s how you can do it:
Explanation
Grid Columns and Rows:
grid-template-columns: 96px 1fr 48px;
defines three columns with specified widths.grid-template-rows: 96px auto 48px;
sets the heights of the rows where:Grid Areas:
grid-template-areas
assigns named areas to the grid items.This approach avoids directly setting the height on the grid items, which can cause the layout to become misaligned. Instead, it leverages the
grid-template-rows
property to control the height of the rows, ensuring the layout remains consistent and the heights are applied correctly.