Imagine this scenario (feel free to copy and paste the code into a new document for better visualization):
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
grid-gap: 20px;
}
.item {
background-color: #bfe0f5;
height: 300px;
cursor: pointer;
}
.separation {
margin: 100px 0;
}
<div class="grid">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
<div class="separation"></div>
<div class="grid">
<div class="item"></div>
<div class="item"></div>
</div>
The initial grid functions perfectly. As the window size changes, the columns adjust accordingly.
However, when there are only one or two items in the grid on desktop devices, I want them to be constrained to a maximum width.
Here's how it should appear on desktop:
https://i.sstatic.net/MWOqK.png
On mobile screens, due to limited space, there would likely be one item per row with a larger size than 300px to fill up the available space.
The code above is almost flawless except for cases where there are only one or two items on a desktop screen. Is there a way to modify the code to account for this situation? These specific items should adhere to a max width.
I attempted setting the max-width
property on the items and then disabling it in a media query for mobile screens. However, this resulted in the entire row being clickable despite the specified max width being only 300px.