Search code examples
htmlcssgrid-layout

Is it possible to show Gridlines in CSS?


I'm starting to learn grid layout for CSS. In an ideal world, I would be able to set up a div multiple grid boxes and place my elements inside precisely, giving overlay when I need it (kind of like using stick to grid in Illustrator).

This can be quite difficult without having a visual representation of that grid, is it possible to see one on my live server? I tried 'showing gridlines' with Chrome Dev Tools, however whenever I refresh or make changes they disappear.

Alternatively, is there any better system to use when I want to have a more precise layout consisting of multiple elements and empty space?


Solution

  • As already answered by @ashish-singh, leveraging native browser developer tools is a good choice, like the already mentioned Firefox CSS Grid Inspector, or even the Chrome Inspect CSS Grid layouts feature. They are powerful features which provide important information regarding rendered columns, rows, gap, etc.

    Anyway, if you really want a persistent cross-refresh approach with CSS, I recommend you to use some trick with outline on grid items. I suggest outlines because with them the items can be collapsed with each other (as technically outlines take up no space), and also because showing and hiding outlines on the fly doesn’t trigger browser layouts recalculation (better performance during your tests).

    Here's a simple sample showing that in action:

    .container {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
      gap: 1px;
    }
    
    .item {
      display: grid;
      place-items: center;
      padding: 1rem;
    
      /* Here's the trick: */
      outline: 1px dashed magenta;
    }
    
    .col-span-2 {
      grid-column: span 2 / span 2;
    }
    
    .row-span-2 {
      grid-row: span 2 / span 2;
    }
    <div class="container">
      <div class="item row-span-2">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
      <div class="item col-span-2">5</div>
      <div class="item">6</div>
    </div>