Day 40: unlayered styles

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.


On day 37 we learned that we can get more control over specificity by creating layers. That first, simple example is pretty straightforward, but what happens if we mix layered and unlayered styles?

Let's start nice and simple with a single layer. The border of this quote is red.

<blockquote>
  There's only one Return, okay, and it ain't of the king...
</blockquote>
@layer base {
  blockquote {
    border: 4px solid red;
    padding: 1rem;
  }
}
There's only one Return, okay, and it ain't of the king...

If we add another layer, the border color turns green because a layer defined later in the document has precedence over a layer defined earlier.

@layer base {
  blockquote {
    border: 4px solid red;
    padding: 1rem;
  }
}

@layer component {
  blockquote {
    border-color: green;
  }
}
There's only one Return, okay, and it ain't of the king...

If we add unlayered styles after the second layer, the color turns hotpink. Not because the declaration comes later in the document, but because unlayered styles have the highest priority and always* overwrite layered styles.

*Okay, not always, but we'll talk about that in another post.

@layer base {
  blockquote {
    border: 4px solid red;
    padding: 1rem;
  }
}

@layer component {
  blockquote {
    border-color: green;
  }
}

blockquote {
  border-color: hotpink;
}
There's only one Return, okay, and it ain't of the king...

This means that the color will be hotpink even if the unlayered styles come before the layered styles.

blockquote {
  border-color: hotpink;
}

@layer base {
  blockquote {
    border: 4px solid red;
    padding: 1rem;
  }
}

@layer component {
  blockquote {
    border-color: green;
  }
}
There's only one Return, okay, and it ain't of the king...

See on CodePen

Further reading

Overview: 100 Days Of More Or Less Modern CSS