Search code examples
csscss-grid

How to turn off grid auto adjust to other divs?


After I add anything into the one of the 3 divs others height expands to fit the biggest one is there any way to remove this auto sizing? Code example (box1 and box3 expand to the size of box2):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div class="gridBody">
        <div> box1 (show this without the width of the second line)</div>
        <div> box2<div> second line</div> </div>
        <div> box3 (show this without the width of the second line)</div>
    </div>

    <style>
        .gridBody {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
        }
        .gridBody div {
            margin: 20px;
            padding: 20px;
            background: rgba(0, 0, 0, 0.5);

        }
    </style>
</body>
</html>

I tried grid-auto-rows/grid-auto-columns:min-content and expected it to adjust the size of box1 and box3 to the minimal content but it didn't work


Solution

  • It seems that you could add align-items: start to gridBody to avoid other div expanding height to fit the biggest one.

    By default, grid layout will place the items in a behavior similar to align-items: stretch, which resulted in all div stretched to the full height.

    More about align-items

    Example:

    .gridBody {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      /* 👇 Add this line */
      align-items: start;
    }
    
    .gridBody div {
      margin: 20px;
      padding: 20px;
      background: rgba(0, 0, 0, 0.5);
    }
    <div class="gridBody">
      <div> box1 (show this without the width of the second line)</div>
      <div> box2
        <div> second line</div>
      </div>
      <div> box3 (show this without the width of the second line)</div>
    </div>