Search code examples
csscss-selectors

How to select elements that have a specific css variable defined in its style tag?


Is there a way to select elements that have a specific css variable defined in its style tag? i guess its not available because it would act strange with global variables but maybe there is a way.
for example change this:

<div data-icon style="--icon: url(...)"></div>
<style>
div[data-icon]::before {
    ...
    background-image: var(--icon);
    ...
}
</style>

to something like that:

<div style="--icon: url(...)"></div>
<style>
div:has(var(--icon))::before {
    ...
    background-image: var(--icon);
    ...
}
</style>

Solution

  • Use attribute selector like your first code:

    div[style*="--icon"]::before {
      content: "I have a variable";
      background-image: var(--icon);
    }
    <div style="--icon: url(...)"></div>
    <div></div>