7

At the head of my page, I have a bunch of CSS Custom Properties that work in all of my stylesheets, however, when I try to access them via ::before/::after pseudo-elements, Chrome states that the variable is not defined.

As an example:

<head>
  ...
  <style>
    :root {
      --my-variable: #ff0000;
    }
  </style>
</head>

And in my stylesheets:

.box {
  background-color: var(--my-variable); // Works fine
}

.box::after {
  background-color: var(--my-variable); // --my-variable is not defined
}

Just wondering if I've missed something?

I've also just noticed it works fine with Firefox, so perhaps it's a bug?

Update: So it seems CSS Properties aren't inherited in pseudo-elements so it needs to be set directly as per this answer

Working Example:

:root, *::before, *::after {
  --my-property: xyz;
}
ConduciveMammal
  • 455
  • 7
  • 20
  • 1
    you need to have `content` and add dimension to your pseudo element. This is not related to CSS variables – Temani Afif Mar 16 '22 at 19:20
  • Apologies, my actual work contains the correct rules. The above example was only for brevity. – ConduciveMammal Mar 16 '22 at 20:50
  • works fine on chrome/firefox: https://codepen.io/ste-xx/pen/zYprGXw – ste-xx Mar 17 '22 at 11:29
  • 1
    It *works* fine, but Chrome Inspector still says `--given-color is not defined` if you select the `.given_class::after` pseudo element in the `Elements` tab, observe the `Styles` pane, and hover your cursor over "`--given-color`" in `content: var(--given-color)` (in your example at https://codepen.io/ste-xx/pen/zYprGXw) – Dirk Diggler Aug 30 '22 at 21:04
  • I second this! While the variable is resolved correctly in the Pseudo Elem. Chrome/Edge still say the variable is undefined despite rendering it correctly. – BaSsGaz Feb 10 '23 at 14:52

0 Answers0