I have CSS Grid which has 7 columns and multiple rows. Is it possible to have first 4 columns occupying same width as last 3 columns when column width is dynamic?
In example below, I explicitly set grid-template-columns
to specific widths to reproduce final result I want, but in real case scenario, I need to have dynamic width columns and grid, but first 4 columns should always be equal width to other 3 columns.
.grid {
display: grid;
width: 720px;
grid-template-columns: repeat(4, 3fr) repeat(3, 4fr);
>div {
border: 1px solid gray;
}
.expl1 {
grid-column: 1/span 4;
}
.expl2 {
grid-column: 5/-1;
}
}
<div class="grid">
<div>Col 1</div>
<div>Col 2</div>
<div>Col 3</div>
<div>Col 4</div>
<div>Col 5</div>
<div>Col </div>
<div>Col 7</div>
<div class="expl1">Above width is 4 * 90px = 360px</div>
<div class="expl2">Above width is 3 * 120px = 360px</div>
</div>
Is there any solution without splitting grid into two columns and putting subgrid of 4 columns into first column and subgrid of 3 columns into second column?
2
Answers
Sure but don’t use
repeat
Yes, you can achieve this without splitting the grid into two columns or using subgrids. The key is to use fractional units
(fr)
in thegrid-template-columns
property while ensuring that the sum of the fractions for the first four columns is equal to the sum of the fractions for the last three columns.