Search code examples
csssass

Using sass variables in css grid template


I am trying to set up a page layout with css grid. I am using scss. When I want to use a scss variable for grid-template, the layout breaks.

$page-header-height: 3rem;
$content-header-height: 6rem;
$content-menu-width: 10rem;

// if i try to use these, the layout breaks
$content-foot-height: 4rem;
$page-sidebar-width: 4rem;

body {
  height: 100vh;
  display: grid;
   grid-template:
    'sidebar header header' $page-header-height
    'sidebar menu mainHead' $content-header-height
    'sidebar menu main' 1fr
    // here should be foot height  / sidebar width     
    'sidebar menu mainFoot' 4rem / 4rem $content-menu-width; // < problem
  > * {
    border: thin groove gray;
  }
}

Why does the layout break when using the variables, which hold the exact same value? On top of that all the other variables work.

Here is the code, you can plug the variables in and see it break.

https://codepen.io/bluebrown/pen/NWqBYvq


Solution

  • Your layout breaks because when writing $content-foot-height / $page-sidebar-width SASS is doing the calculation 4rem/4rem and returns 1, which invalidates your grid-template property.

    You can use interpolation on one or both of these variables to avoid this problem:

    #{$content-foot-height} / #{$page-sidebar-width} $content-menu-width;