I want to override base-font-size by calling a function, its definition is given below
base-font-size variable is defined in the root
export const changeBaseFontSize = (newSize: string) => {
document.documentElement.style.setProperty("--base-font-size", newSize);
};
Calling this function as given below
changeBaseFontSize("16");
Now, I have a function which will convert the provided pixel value into rem depending upon the base-font-size value
@function pxToRem($pxValue) {
$baseFont: var(--base-font-size);
$remValue: #{$pxValue / $baseFont};
@return $remValue + rem;
}
Now when I am calling this function from scss file as given below
.n-code-input-field {
border-radius: pxToRem(16);
}
When I am running this code it is applying the styles as given below
.n-code-input-field {
border-radius: 16/var(--base-font-size)rem;
}
These border styles are not working
but If I directly add the base-font-size as 16 it is working fine
@function pxToRem($pxValue) {
$baseFont: 16;
$remValue: #{$pxValue / $baseFont};
@return $remValue + rem;
}
This is working fine as it is returning 1rem
@function pxToRem($pxValue) {
$baseFont: 16;
$remValue: #{$pxValue / $baseFont};
@return $remValue + rem;
}
border-radius: 1rem;
How Can I fix it?
Ideally It should return the calculated rem value
2
Answers
That’s not possible as it would require time travel. Literally.
You are trying to read a CSS variable’s value (only available at run-time) inside SCSS functions (which run at build-time).
By the time the CSS value has been populated (by DOM inheritance), the SCSS has already been compiled into CSS. Which means the functions you’re writing would have already been run.
Another way to put it: SCSS gets compiled into CSS on the server. CSS variables are populated in the browser. You’re trying to read on the server values which will be populated when the CSS is run by the browser.
As mentioned by Amaury Hanser you can return a calc value. Note the fallback value in var(–base-font-size, 16) in case –base-font-size is not defined
Demo of output* (to show downvoters it works 😉
*stack overflow does not support Sass