Hide overflowing items in CSS Grid

Viewed 625

I am trying to achieve a specific layout of images that depends on the width of the viewport.

Essentially I would like this: image layout desired

I have an array of images and have been experimenting with css grid, but have issues with overflow.

For example, say I have 12 images for the desktop layout, I can organise the layout fine with the columns and rows, but when resizing I only want there to be ~3 images displayed in a single row, as per the image^. However, when viewing on a smaller device, the remaining images get pushed into a new row, and I cannot work out how to 'hide' the overflow and force the the grid to render only one row.

How can I go about limiting the number of rows/items depending on screen size?

One option would be to detect the size of the screen using the screen width breakpoints, and simply limit the number of items in the array. This would remove the issue of overflowing elements, but this feels messy.

Does anyone have any better suggestions as to how I can hide the extra elements? and force it to be 1 row only when required?

2 Answers

Assuming you have bunch of <img> tags in your grid and you want only 3 of them to be displayed, you can use CSS to hide additional images as well as reset the grid template to better match what is expected:

@media (max-width: 768px) {
    #container {
        grid-template-columns: 1fr 1fr 1fr;
    }
    #container img:nth-child(n+4) {
        display: none;
    }
}

However, beware that it will still cause network usage since the <img> will still be a part of DOM.

You can use CSS media queries, for instance, if this is your original code for the grid system: (This is based on your first outcome)

.my-grid {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
}

This will divide the grid system into 3 columns, this is shown by the 1fr which is basically a fraction ... out of the total 3, which means one element will occupy 1/3 of the total width(columns). For larger devices, use media queries:

@media screen and (min-width: 800px) {
    .my-grid {
        grid-template-columns: 1fr 1fr 1fr 1fr;
        /* each element will occupy 1/4 of the width */
    }
}

Then for extra large devices, just increase the size of the min-width, which in this case is the minimum width of the device you are targetting:

@media screen and (min-width: 1200px) {
    .my-grid {
         grid-template-columns: 1fr 1fr 1fr 1fr 1fr 1fr;
         /* each element will occupy 1/6th of the width */
    }
}

And for instance you only want to have 1 row as you've mentioned, using grid-temaplate-rows will style the elements in a horizontal position, such that you can define the number of rows you want to show up in your grid system:

.my-grid {
     grid-template-rows: 1fr;
}

This will limit the rows to only 1, for 2 rows it becomes grid-template-rows: 1fr 1fr; ... and so on

Related