Search code examples
csstailwind-csscss-grid

CSS Grid - make items scrollable instead of shrinking them to fit


I'm working with a CSS Grid and, in case of an overflow, I would like the elements to scroll both vertically and horizontally, so it "zooms" in. However, the elements are shrinking themselves to fit the grid, and it creates two problems:

  1. The elements are super small
  2. The contents of squares overflow each other

This is my code for components:

BoardContainer.tsx

import {FC, ReactElement, useState} from "react";

import Square from "@/components/board/Square";

const BoardContainer: FC = () => {
    const boardSquares: ReactElement[] = [];
    for (let i : number = 0; i < 2601; i++) {
        boardSquares.push(<Square key={i} i={i}/>);
    }

  return (
      <div className="board-container h-[92.5%] w-[60%] overflow-scroll">
        <div className="grid grid-cols-51 grid-rows-51">
          {boardSquares}
        </div>
    </div>
  );
};


export default BoardContainer;
Square.tsx:

import {ReactElement} from "react";

const Square = ({i} : {i: number}): ReactElement => {
    return (
    <div className={"flex justify-center border border-gray-200 aspect-square"}>
        {i}
        </div>
    )
}

export default Square;

Solution

  • grid-cols-51 and grid-rows-51 classes do not exist in Tailwind by default. You may have some custom configuration that you failed to provide. Regardless, presuming these classes should apply 51 grid column tracks and rows respectively, consider having the grid track sizing to be auto or max-content to avoid any shrinking:

    const { useState} = React;
    
    const Square = ({i}) => {
      return (
        <div className={"flex justify-center border border-gray-200 aspect-square"}>
          {i}
        </div>
      )
    }
    
    const BoardContainer = () => {
      const boardSquares = [];
      for (let i : number = 0; i < 2601; i++) {
        boardSquares.push(<Square key={i} i={i}/>);
      }
    
      return (
        <div className="board-container h-[92.5%] w-[60%] overflow-scroll">
          <div className="grid grid-cols-[repeat(51,max-content)] grid-rows-[repeat(51,max-content)]">
            {boardSquares}
          </div>
        </div>
      );
    };
    
    ReactDOM.createRoot(document.getElementById('app')).render(<BoardContainer/>);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.tailwindcss.com/3.4.1"></script>
    
    <div id="app"></div>