I'm trying to use the calc()
function in a Sass stylesheet, but I'm having some issues. Here's my code:
$body_padding: 50px body padding-top: $body_padding height: calc(100% - $body_padding)
If I use the literal 50px
instead of my body_padding
variable, I get exactly what I want. However, when I switch to the variable, this is the output:
body { padding-top: 50px; height: calc(100% - $body_padding); }
How can I get Sass to recognize that it needs to replace the variable within the calc
function?
On top of using CSS variables in calc you can also convert a value that has no units to a value with units by just multiplying the value by 1 of the unit type you want to convert to. This is very useful if you have CSS variables being set in JS that do not include the unit.
calc() The calc() CSS function lets you perform calculations when specifying CSS property values. It can be used anywhere a <length> , <frequency> , <angle> , <time> , <percentage> , <number> , or <integer> is allowed.
To convert the SASS variable to a CSS custom property you put curly brackets around it, and a hash in front. If you've used template literals in JavaScript it's the same thing, just with a # instead of a $ (because we already have $ in the variable name).
CSS variables are included in the CSS output. CSS variables can have different values for different elements, but Sass variables only have one value at a time. Sass variables are imperative, which means if you use a variable and then change its value, the earlier use will stay the same.
Interpolate:
body height: calc(100% - #{$body_padding})
For this case, border-box would also suffice:
body box-sizing: border-box height: 100% padding-top: $body_padding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With