UXerUIer
UXerUIer

Reputation: 2338

Calculating column widths with css's calc + sass

I'm attempting to output a calculated percentage number using CSS's calc, in addition to SASS to scale column calculations like so:

Variables:

//Gutter values
$grid__gutter-lg            :                20px;
$grid__gutter-md            :                20px;
$grid__gutter-sm            :                20px;
$grid__gutter-xsm           :                10px;

//Column values
$grid__columns-lg           :                12;
$grid__columns-md           :                12;
$grid__columns-sm           :                6;
$grid__columns-xsm          :                2;

Function for variables:

 @function round-width ($i, $grid-columns, $gutter) {
  $g_val : $gutter / 1px;
  $width : calc((100 * #{$i} / #{$grid-columns})#{"%"} - (#{$g_val} *  (#{$grid-columns} / #{$i} - 1) / (#{$grid-columns} / #{$i}))#{"px"});
  @return $width;
}

The round-width is then fed to the for loop to create on the fly columns in classes:

@for $i from 1 through $grid__columns-lg {
  .col__lg-#{$i} {
    flex-basis: round-width($i, $grid__columns-lg, $grid__gutter-lg);
    max-width: round-width($i, $grid__columns-lg, $grid__gutter-lg);
  }
}

The issue is that I get the following error of invalid property value.

And example of the output error:

.col__lg-6 {
    flex-basis: calc( (100 * 6 * 12)% - (20 * 12 / 6 - 1 / 12 / 6)px );
    max-width: calc( (100 * 6 * 12) % - (20 * 12 / 6 - 1 / 12 / 6) px);
}

I thought adding the percentage and pixel outputs will help "validate" the output, but I guess not? I also have the spaces, and it still errors out.

Upvotes: 2

Views: 1277

Answers (1)

mfluehr
mfluehr

Reputation: 3187

CSS can't parse values with the unit outside a set of parentheses, e.g., calc((10)% + (5)px). Instead, CSS needs the units directly attached to their respective numbers, e.g., calc(10% + 5px).

Here's a fix for your round-width() function:

@function round-width ($i, $grid-columns, $gutter) {
  $g_val : $gutter / 1px;
  $width : calc(
    #{100 * $i / $grid-columns}% -
    #{$g_val * ($grid-columns / $i - 1) / ($grid-columns / $i)}px
  );
  @return $width;
}

The above SCSS compiles to valid CSS, like this:

.col__lg-6 {
  flex-basis: calc( 50% - 10px );
  max-width: calc( 50% - 10px );
}

Upvotes: 2

Related Questions