Reputation: 3995
I am trying to display fields in a row in the following form: Display 3 fields in a row with equal width, and the rest of them, if I have 2 fields to be in a row with equal width, and if there is one field left to be full width
I tried with this CSS:
root: {
width: '100%',
display: 'grid',
gridTemplateColumns: 'repeat(3, 1fr)',
gridColumnGap: theme.spacing(),
overflow: 'hidden',
},
But this is the result I got:
How can I achieve the expected result(first image) with CSS grid?
Upvotes: 1
Views: 1125
Reputation: 6837
I can think of two solutions for this. First instead of dividing the grid to 3 columns, divide to 6 columns and span the grid items into multiple columns by targeting them using nth-child
selector. Second Don't use grid at-all, instead create a flex-container that will have another 3 flex-container as child nodes. And make use of flex-basis
to get the desired result.
Solution 1
Using a 6 column grid,
You have to target specific grid items and make use of span
to span them across n
number of columns. For example for the first 3 grid item you need to specify grid-column: span 2;
. Example,
.grid-container {
display: grid;
grid-template-columns: repeat(6, 1fr);
grid-template-rows: repeat(3, 1fr);
}
.grid-item:nth-child(1),
.grid-item:nth-child(2),
.grid-item:nth-child(3) {
grid-column: span 2;
}
.grid-item:nth-child(4),
.grid-item:nth-child(5) {
grid-column: span 3;
}
.grid-item:last-child {
grid-column: span 6;
}
See the demo in codesandbox.
Solution 2
Since you asked for a solution using CSS-grid, I don't think it is a good idea to include the code for the solution that uses flex-box instead. Have a look at the codesandbox, for the solution using flex-box.
Upvotes: 3