CSS custom properties ('CSS variables') to the rescue
.grid {
--repeat: auto-fit;
}
@media (min-width: calc(250px * 3)) {
.grid {
--repeat: 3;
}
}
.grid {
display: grid;
grid-template-columns: repeat(var(--repeat, auto-fit), minmax(calc(250px * 1) , 1fr));
grid-gap: 8px;
}
.grid .item {
background-color: silver;
padding: 8px;
}
<div class="grid">
<div class="item">Lorem, ipsum.</div>
<div class="item">Soluta, voluptatibus!</div>
<div class="item">Reprehenderit, consequuntur.</div>
<div class="item">Temporibus, veritatis!</div>
<div class="item">Consequatur, voluptates.</div>
<div class="item">Distinctio, adipisci.</div>
<div class="item">Repellat, corrupti.</div>
<div class="item">Quia, corporis.</div>
<div class="item">Nobis, aut.</div>
<div class="item">Dicta, officiis?</div>
<div class="item">Voluptate, tempora?</div>
<div class="item">Nihil, earum?</div>
<div class="item">Placeat, aspernatur!</div>
<div class="item">Officia, sunt?</div>
<div class="item">Atque, temporibus!</div>
<div class="item">Rerum, unde!</div>
<div class="item">Hic, molestias!</div>
<div class="item">Et, repellat!</div>
<div class="item">Earum, itaque.</div>
<div class="item">Doloribus, facilis.</div>
<div class="item">Eius, alias!</div>
<div class="item">Est, officia.</div>
<div class="item">Ad, porro!</div>
<div class="item">Ipsum, voluptates.</div>
<div class="item">Animi, eligendi.</div>
<div class="item">Tempore, hic!</div>
<div class="item">Voluptatibus, illum.</div>
<div class="item">Autem, cumque!</div>
<div class="item">Cupiditate, minus!</div>
<div class="item">Tenetur, aliquam.</div>
</div>
Remark
The asker wanted in his OP a solution which would not use media queries. This solution does use media queries, but in a somewhat different way. The only thing that is changed in the media query is the value of a CSS custom property.
We could even use a 'global' custom property with the :root
selector
:root {
--repeat: auto-fit;
}
@media (min-width: calc(250 * 3px)) {
:root {
--repeat: 3;
}
}
One could think further and use custom properties in the media query condition itself, but unfortunately this does not work. (See this answer)
/* not working */
:root {
--repeat: auto-fit;
--max-columns: 3;
--max-column-width: 250px;
}
/* Will not work: var is not allowed in media query condition */
@media (min-width: calc(var(--max-column-width) * var(--max-columns))) {
:root {
--repeat: var(--max-columns);
}
}