Struggling to grasp a CSS calculation that evenly spaces children in a flexed container with a defined gap between them? You're not alone!
I'm looking to streamline this process by creating a SASS(SCSS) function for the calculation, but I can't wrap my head around it.
Here's the current calculation:
.my-class {
--columns: 3;
--gap: 16px;
width: calc((1 / var(--columns) * 100%) - ((1 - 1 / var(--columns)) * var(--gap)));
}
Below is an example demonstrating how this works within a fixed-width container (768px wide).
.toCalc {
--cols: 3;
--gap: 16px;
width: calc((1 / var(--cols) * 100%) - ((1 - 1 / var(--cols)) * var(--gap)));
background: blue;
height: 150px;
}
.container {
width: 768px;
height: 300px;
background: grey;
display: flex;
gap: 16px;
}
<div class="container">
<div class="toCalc">
This is content
</div>
<div class="toCalc">
This is content
</div>
<div class="toCalc">
This is content
</div>
</div>
Trying to convert this to SCSS has proven challenging:
@function calcWidth($cols, $gap) {
@debug "1/cols: #{1/$cols}";
@debug "(1/cols) * 100%: #{(1/$cols) * 100%}";
@debug "1 - (1/cols): #{1 - (1/$cols)}";
@debug "(1 - (1/cols)) * gap: #{(1 - (1/$cols)) * $gap}";
$result = ((1/$cols) * 100%) - ((1 - (1/$cols)) * $gap);
@debug "full result: #{$result}";
@return $result;
}
...
.my-class {
// Converted css properties (--var) to SCSS variables ($var)
$cols: 3;
$gap: 16px;
width: calcWidth($cols, $gap);
}
When using cols = 3
and gap = 16px
, the debug messages show:
DEBUG: 1/cols: 0.33333
DEBUG: (1/cols) * 100%: 33.33333%
DEBUG: 1 - (1/cols): 0.66667
DEBUG: (1 - (1/cols)) * gap: 10.66667px
DEBUG: full result: 22.66667px // <------------ This is not the same as we see?!
The debug messages seem technically correct, so why does the code give us a width value of 245.33px
instead?
Update
I realized I left out the %
from the function calculation initially.
However, upon adding it back in, SASS throws an error about incompatible units:
SassError: Incompatible units: 'px' and '%'.