Let’s say I have a container with display: grid
. I want to make sure that each column takes up the following widths depending on how many columns there are:
- If 2 or less, each column takes up
1/2
. - If greater than 2, each column takes up
1/3
I have the following code so far:
.container {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 8px;
border: 1px solid black;
padding: 8px;
}
.column {
grid-column: span 4 / span 4;
border: 1px solid red;
padding: 8px;
}
<div class="container">
<div class="column">Column</div>
<div class="column">Column</div>
<div class="column">Column</div>
</div>
It works for the most part, as in it takes care of the most common use case where each column takes up 1/3 width. But I would love to make this dynamic based on the number of columns present. Is there a way to do this?
2
Answers
To achieve the desired layout where each column takes up 1/2 of the container’s width when there are 2 or fewer columns, and each column takes up 1/3 of the container’s width when there are more than 2 columns, you can use CSS Grid and media queries. Here’s how you can modify your code:
Yes, this is possible (based on this SO Q&A)