Search code examples
sasscss-calc

Sass calc decleration dropped Chrome


I am writing a simple grid layout using Sass. I am trying to use calc() to determine the width in relative units %. To test the styles, I am using a simple HTML file.

Problem: Inspecting the results with dev tools on Chrome, it shows that the width declaration with the calc() call is dropped as Invalid property value. Here is the code:

src.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="X-UA Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width initial-scale=1.0">
        <link rel="stylesheet" type="text/css" href="./../css/12grid_rwd.css">
    </head>
    <body>
        <main class="grid_1" role="main">
            <!--<header class="grid_12" role="banner">Header</header>
            <nav class="grid_3" role="navigation">Nav</nav>
            <section class="grid_9">Content</section>
            <footer class="grid_12" role="contentinfo">Footer</footer> -->
        </main>
    </body>
</html>

src.scss

$context-width: 1200;
// Grid >> 12 Columns
.grid {
    &_1 { width: calc(calc(80/#{$context-width})*100); }
}

generated css:

.grid_1 {
  width: calc(calc(80/1200)*100); }

Solution

  • calc() call's can't be nested, it expects expression to calculate, it is the reason why your property is dropped by browser.

    Moreover since your expression contains plain math - it can be calculated by Sass itself. Moreover from your expression it looks like you want resulted value to be percent from container's width, in this case you can use percentage() function from Sass:

    $context-width: 1200;
    $column-width: 80;
    // Grid >> 12 Columns
    .grid {
      @for $n from 1 through 12 {
        &_#{$n} { 
          width: percentage($column-width * $n/$context-width); 
        }
      }
    }
    

    You can play with this example at Sassmeister.