How to make effective use of CSS custom properties?
P粉384366923
P粉384366923 2024-01-16 19:00:56
0
1
395

I am developing an application with a custom theme setting that allows the user to select the primary colors that the application uses to generate a set of 10 Tailwind style color variables. I use javascript to generate colors and inject them into the dom, but in my research I found out that it is not possible to inject scss variables because the dom only has access to the compiled css. So I had to use css custom properties instead of scss colors.

I know this is an unusual use case and not the way scss works with colors, but I'm hoping to find an efficient solution to the problem rather than rewriting my project.

html {
    // Default Colors
    --color-primary-50: #F2F5FD;
    --color-primary-100: #E4EAFB;
    --color-primary-200: #C5D2F7;
    ...
}
const setPalette = function setPaletteCSS(palette) {
    Object.entries(palette).forEach((entry) => {
        const [step, color] = entry;
        document.documentElement.style.setProperty(
            `--color-primary-${step}`, 
            color
        );
    });
}

The code worked perfectly, but now my main.scss file became too big and I split it using the 7-1 architecture pattern which worked fine for the rest of the scss file until I try to move these colors around. Specifically, I moved the html component with custom colors to abstracts/_colors.scss:

.
└── scss/
    ├── abstracts/
    │   ├── _colors.scss
    │   └── _index.scss
    └── main.scss

The main problem I have is that my component accesses these variables like this:

#site-header, #site-footer {
    color: var(--font-color);
    background-color: var(--color-primary-500);
}

I added abstracts/colors to my main.scss like any other component, but I can no longer access the color properties .

@use './abstracts' as a;

#site-header, #site-footer {
    color: a.var(--font-color);
    background-color: a.var(--color-primary-500);
}
This causes webpack to fail to compile my scss and displays the following error:

Module build failed (from ./node_modules/sass-loader/dist/cjs.js):
SassError: Undefined function.
   ╷
49 │     color: a.var(--font-color);
   │            ^^^^^^^^^^^^^^^^^^^
   ╵

I understand the error, but I don't know what the options are to resolve it. Since I'm stuck on using css custom properties for colors, is there a way to

@use

them, or am I stuck on keeping all color-related css in the same file?

P粉384366923
P粉384366923

reply all(1)
P粉600402085

I haven't found a way to use SCSS namespaces with CSS variables. It will work if you @use './abstracts' as *;. This article provides a good example on how to create a theme using scss.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template