Skip to content
This repository was archived by the owner on Dec 19, 2024. It is now read-only.
This repository was archived by the owner on Dec 19, 2024. It is now read-only.

Should custom properties be ignored when not scoped to :root? #186

@Zacqary

Description

@Zacqary

Just started playing around with cssnext, and I immediately got this error when testing out what happened when I assigned something a custom property:

› cssnext: <css input>:4:2: Custom property ignored: not scoped to the top-level :root element (header { ... --test: ... })

So I see what this is about. Custom properties, when used for var(), want to be placed inside :root so that they're globally available. But var() isn't the only reason why you might want to use custom properties.

I haven't seen a lot of people connecting the dots and talking about this, but custom properties are incredibly useful for writing web components. Here's a situation I ran into a few days ago:
<pie-chart percent="33"></pie-chart>

This is a custom element that extends <canvas>, and will draw a pie chart to itself based on the value of the percent attribute. The thing is, the JS to do this needs to be passed two different colors: the color of the empty section of the pie chart, and the color of the full section. I wanted to be able to do this with CSS. I was left with having to use the various color properties in non-standard ways. For example, I'd render the canvas with something like:

drawEmptyPortion();
context.fillStyle = document.querySelector('pie-chart').style.backgroundColor;
context.fill();
drawFullPortion();
context.fillStyle = document.querySelector('pie-chart').style.color;
context.fill();

and then

pie-chart {
    color: #f00; // The full color
    background-color: #888; // The empty color
}

But that creates a problem of giving the entire canvas a gray background instead of rendering everything surrounding the pie chart transparent. So instead, I had to use:

outline-color: #888;

Thankfully, I didn't also need to render my pie chart with a CSS outline, so this variable was otherwise unused. Also the color variable, because there was no text. But that's a lucky situation, and this is still a hack using CSS properties in a non-standard way. What I'd really like to be able to do is:

pie-chart {
    --full-color: #f00;
    --empty-color: #888;
}

Unfortunately, cssnext isn't equipped to handle that kind of situation. I don't know if this sort of behavior is outside the scope of cssnext, vis-a-vis exposing custom properties to JS for this kind of purpose, but it's something that I think a lot of people will be increasingly exploring as web components become more popular. So it's a question I'd at least like to discuss.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions