Highlight CSS Grid

I have CSS Grid:

<div style="display:grid;grid-template-columns:repeat(5, 1fr);grid-template-rows:repeat(5, 1fr);align-items: center;justify-items: center;" sc-part-of="placeholder rendering" class="scEnabledChrome">

when I inspect grid in Chrome DevTools I have next highlighting effect: enter image description here

How can I achieve similar effect using CSS or JavaScript? I want to have ability to show/hide lines that divide grid.

1 answer

  • answered 2018-08-15 14:31 Temani Afif

    Here is an idea using gradient to have similar effect (but without the dashes). You simply need to adjust the values of the gradient to make it the same as the repeat:

    .box {
      height: 200px;
      display: grid;
      grid-template-columns: repeat(5, 1fr);
      grid-template-rows: repeat(5, 1fr);
      align-items: center;
      justify-items: center;
      border-top:1px solid;
      border-left:1px solid;
      background: 
       repeating-linear-gradient(to right, transparent 0,transparent calc(100%/5 - 1px),#000 calc(100%/5 - 1px),#000 calc(100%/5)),
       repeating-linear-gradient(to bottom,transparent 0,transparent calc(100%/5 - 1px),#000 calc(100%/5 - 1px),#000 calc(100%/5));
    }
    <div class="box"></div>

    You may also consider CSS variable to make it easy:

    .box {
      height: 200px;
      display: grid;
      grid-template-columns: repeat(var(--c,5), 1fr);
      grid-template-rows: repeat(var(--r,5), 1fr);
      align-items: center;
      justify-items: center;
      border-top:1px solid;
      border-left:1px solid;
      background: 
       repeating-linear-gradient(to right, transparent 0,transparent calc(100%/var(--c,5) - 1px),#000 calc(100%/var(--c,5) - 1px),#000 calc(100%/var(--c,5))),
       repeating-linear-gradient(to bottom,transparent 0,transparent calc(100%/var(--r,5) - 1px),#000 calc(100%/var(--r,5) - 1px),#000 calc(100%/var(--r,5)));
    }
    <div class="box"></div>
    <div class="box" style="--c:3;--r:4"></div>