Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide overflowing items in CSS Grid [closed]

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?

like image 769
harveyives Avatar asked Oct 13 '25 07:10

harveyives


1 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.

like image 90
Muhammad Talha Akbar Avatar answered Oct 14 '25 21:10

Muhammad Talha Akbar