CSS custom properties and SASS variables both store values to reuse in styles. They help keep code clean and easy to change.
CSS custom properties vs SASS variables
/* CSS custom property */ :root { --main-color: #3498db; } /* SASS variable */ $main-color: #3498db;
CSS custom properties start with two dashes and live inside selectors like :root.
SASS variables start with a dollar sign and are used in SASS files before compiling to CSS.
--padding is defined and used with var(--padding).:root {
--padding: 1rem;
}
.box {
padding: var(--padding);
}$padding is defined and used directly in styles.$padding: 1rem; .box { padding: $padding; }
:root {
--color: red;
}
.button {
color: var(--color);
}
/* Later in JS, you can change --color dynamically */$color: red; .button { color: $color; } /* SASS variables cannot change after compilation */
This example shows how CSS custom properties define colors in :root and are used in styles. The background and text colors come from the variables.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>CSS Custom Properties vs SASS Variables</title> <style> :root { --main-bg-color: #f0f8ff; --main-text-color: #333; } body { background-color: var(--main-bg-color); color: var(--main-text-color); font-family: Arial, sans-serif; padding: 2rem; } .box { background-color: var(--main-text-color); color: var(--main-bg-color); padding: 1rem; border-radius: 0.5rem; max-width: 300px; margin-top: 1rem; } </style> </head> <body> <h1>Using CSS Custom Properties</h1> <div class="box">This box uses CSS custom properties for colors.</div> </body> </html>
CSS custom properties work in the browser and can be changed with JavaScript.
SASS variables exist only during development and are replaced with actual values when CSS is created.
Use CSS custom properties for dynamic theming and SASS variables for static values during build.
CSS custom properties are live in the browser and start with --.
SASS variables start with $ and are replaced before the browser sees the CSS.
Choose CSS variables for dynamic changes and SASS variables for fixed values during development.