skip to Main Content

I am getting into GRID and FLEX and trying very hard to abandon just DIVS with floats.

Does anyone know if there is a way to determine (JQUERY is fine) if a GRID layout has collapsed into just one column? If I can tell this, then I can do things like CENTER it (which I wouldn’t want to do if it was one of 6 columns) or turn off hover effects (which wouldn’t really be necessary and are pretty ugly when there’s only 1 choice/1 column).

I am not looking for a media query on screen width; but rather a way to factually see if its one column or not, regardless of screen width.

Thanks!

2

Answers


  1. You can check if the child width matches the parents width:

      const grid = document.querySelector(".grid");
      const isSingleColumn = grid.offsetWidth === grid.firstElementChild?.offsetWidth;
    

    Only works when you have no alignment though.

    Login or Signup to reply.
  2. This checks if the grid has collapsed into a single column by comparing the vertical positions of the first two grid items. If their offsetTop values are different, it means they are on different rows, indicating a single-column layout.

    function checkSingleColumnGrid(gridItemSelector) {
        var gridItems = document.querySelectorAll(gridItemSelector);
        if (gridItems.length < 2) {
            // not enough grid items to determine the layout
            return false;
        }
        var firstItem = gridItems[0];
        var secondItem = gridItems[1];
        return firstItem.offsetTop !== secondItem.offsetTop; // compare vertical position
    }
    
    window.addEventListener('resize', function() {
        if (checkSingleColumnGrid('.grid-container > div')) {
            // single column
        } else {
            // multiple columns
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search