I am new to using grid in CSS and there are still some concepts that I don't quite understand. Below is the container I am working with:
<section class="css-grid">
<div class="css-item"><img src="1.jpg" /></div>
<div class="css-item"><img src="2.jpg" /></div>
<div class="css-item"><img src="3.jpg" /></div>
<div class="css-item"><img src="4.jpg" /></div>
<div class="css-item"><img src="5.jpg" /></div>
<div class="css-item"><img src="6.jpg" /></div>
</section>
Accompanied by the following CSS code:
section.css-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
grid-template-rows: 1fr;
column-gap: $gap-5px;
}
img {
width: 100%;
cursor: pointer;
}
Currently, this setup works perfectly for a single line of images, fitting 6 images with a minimum width of 250px or maximum available space evenly among them. However, I need to achieve a specific layout behavior when the screen size is reduced.
- If there is only one image, it should occupy the entire width (1fr).
- If there are two images, they should split the width equally (1fr and 1fr).
- This pattern continues for more images in a row, maintaining an equal distribution.
I have tried adjusting the grid-template-rows: 1fr
property with no success, as well as experimenting with grid-auto-columns
. While I am still learning about CSS grid, these nuances escape me at the moment. Can anyone provide some guidance on this matter?
Thank you,
--
Edit - Additional Information
I apologize for any confusion in my explanation; I am struggling to articulate my thoughts clearly.
To clarify further, here is what the current layout looks like:
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
You can view an example here.
Through media queries, I aim to adjust the layout behaviour when the screen size decreases below a certain threshold, such as 1300px. In such cases where elements do not fit within the designated width, I want them to occupy the full width and share space if necessary.
I initially believed my primary line (grid-template-columns) was sufficient but realized it wasn't. Therefore, I attempted something like:
@media screen and (max-width: 1300px) {
grid-template-columns: 1fr;
}
However, this approach did not yield the desired outcome.
The goal is for the layout to adapt as follows:
- If there is one image, it should fill the entire width (example)
- For two images, they each take up 50% width (two images)
- When three images are displayed, they should adjust accordingly(three images)
I hope this clarifies my query slightly, though I understand it may still be unclear.