Search code examples
htmlcsscss-variables

Why isn't my CSS fallback value being applied?


What I'm trying to do is whenever I delete the variable --mainColor in the :root the border-color will change to black and text to red but it will be the same as the fallback value of the color. Why does this happen?

div {
  width: 500px;
  margin: 10px;
  border-color: var(--mainColor, black);
  color: var(--mainColor, red);
  padding: var(--mainPadding, 10px);
  border: solid;
}
<div>Element</div>
<div>Element</div>
<div>Element</div>

enter image description here


Solution

  • Becase you're overriding the border-color using border property, which uses currentColor by default if you don't specificy color.

    :root {
    }
    
    div {
      width: 500px;
      margin: 10px;
      border: solid; /* moved here */
      border-color: var(--mainColor, black);
      color: var(--mainColor, red);
      padding: var(--mainPadding, 10px);
    }
    <div>Element</div>
    <div>Element</div>
    <div>Element</div>

    Or use border-style instead of border to prevent overriding.

    :root {
    }
    
    div {
      width: 500px;
      margin: 10px;
      border-color: var(--mainColor, black);
      color: var(--mainColor, red);
      padding: var(--mainPadding, 10px);
      border-style: solid;
    }
    <div>Element</div>
    <div>Element</div>
    <div>Element</div>