Reputation: 6505
I am trying to make a grid in which columns dynamically adapt to the screen size. The most important criteria is that I want just 1 column on mobile devices or browsers on pc with similar dimensions, more columns can be added when the browser window grows in width.
I have been using a grid to implement this:
.App {
margin: 10px;
text-align: center;
display: grid;
grid-gap: 10px;
justify-items: stretch;
grid-template-columns: repeat(auto-fit, minmax(?, ?)); /* Should change */
}
All the content in the grid have same width and look like the following sketched out:
For the specific width of the children of the grid, I was thinking about the
minmax
function to decide whether it should just fill the full viewport width or not, but I hit a rock there. Because if I use something like minmax(25vw, 100vw)
then I'd always have a width of 100vw
because nothing is preventing it from not being full width.
I am not a css guy and don't have too much experience with it so if I said something completely stupid, don't hesitate to point it out!
Upvotes: 2
Views: 2249
Reputation: 339
If I'm understanding you correctly, then media queries should be the solution to your problem. They allow you to specify rules that only apply for certain screen sizes (or other conditions).
In your case let's assume you want one column on all devices that have a maximum width of 720px
and if they are larger just fit as many columns in the grid as possible (correct me if I'm wrong!).
Then we could use this for all small screens:
@media (max-width: 720px) {
.grid {
grid-template-columns: repeat(auto-fill, 720px);
}
}
and use grid-template-columns: repeat(auto-fill, 200px);
where 200px
is the width of our items for example for all other cases.
See below for an example:
body {
margin: 0;
}
.grid {
width: 100%;
margin: 1rem auto;
display: grid;
justify-items: center;
grid-gap: 10px;
justify-content: center;
grid-template-columns: repeat(auto-fill, 200px);
}
.item {
width: 200px;
height: 200px;
border: 1px solid #333;
background-color: #aaa;
}
@media (max-width: 720px) {
.grid {
grid-template-columns: repeat(auto-fill, 720px);
}
}
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
Note: use "Full Page" to see it working with a larger width
.
Upvotes: 3