The paragraph is green. Why?

I came across this sort of “CSS riddle” recently.

It goes something like this.

Given this CSS definition,

body {
  max-width: 28em;
  margin: auto;
  padding: 1em;
}

html {
  --color: green;
}

body {
  color: yellow;
}

p {
  --color: inherit;
  color: red;
  color: var(--color, blue);
}

what would be the color of the <p> element?

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent bibendum, lorem vel tincidunt imperdiet, nibh elit laoreet felis, a bibendum nisl tortor non orci. Donec pretium fermentum felis, quis aliquet est rutrum ut. Integer quis massa ut lacus viverra pharetra in eu lacus. Aliquam tempus odio adipiscing diam pellentesque rhoncus. Curabitur a bibendum est. Mauris vehicula cursus risus id luctus. Curabitur accumsan venenatis nibh, non egestas ipsum vulputate ac. Vivamus consectetur dolor sit amet enim aliquet eu scelerisque ipsum hendrerit. Donec lobortis suscipit vestibulum. Nullam luctus pellentesque risus in ullamcorper. Nam neque nunc, mattis vitae ornare ut, feugiat a erat. Ut tempus iaculis augue vel pellentesque.</p>

Source: https://codepen.io/shshaw/pen/wvJmOOq

ANSWER

The output color is Green. As if the title wasn’t a giveaway.

Try it out yourself too.

Here is an explanation: https://twitter.com/SelenIT2/status/1400832345016606722

Quoting from that Tweet:

It does inherit it. But then the color gets overridden with the inherited value of the *custom property* named `–color`, which doesn’t know anything about the actual `color` property and gets independently inherited all the way down from `html`

Leave a Reply

Your email address will not be published. Required fields are marked *