Sub topic 9
Containing third-party and framework CSS
This chapter assumes you can declare layers with @layer blocks and an order statement. It also assumes you know that unlayered normal declarations beat layered ones, and that you can read specificity. Here you apply those rules to CSS you did not write: frameworks, component libraries, and widgets.
The problem with code you don't control
A framework stylesheet comes with specificity you did not choose. It may use .navbar .nav-link.active, #widget .btn, or a long chain of attribute selectors. To override it without layers, you have to out-score those selectors. That leads to wrapper IDs, doubled classes such as .btn.btn, or !important. Each workaround raises the specificity floor for the next override.
Cascade layers remove the contest. If the framework sits in a layer that is declared before your layers, every rule of yours wins, whatever the selectors look like. The framework's internal specificity still applies, but only among the framework's own rules.
/* vendor.css, not yours to edit */
#app .btn.btn-primary {
background: #0d6efd;
padding: 0.75rem 1.5rem;
}/* site.css */
@layer vendor, site;
@import url("vendor.css") layer(vendor);
@layer site {
.btn { background: rebeccapurple; }
}The .btn rule has specificity (0,1,0). The vendor rule has (1,2,0). The button is still purple, because site is declared after vendor and layer order is compared before specificity.
Import a file into a layer
The layer() function on @import puts the whole imported file into a named layer.
@layer reset, vendor, base, components, utilities;
@import url("normalize.css") layer(reset);
@import url("framework.css") layer(vendor);Three rules matter here:
@importmust come before every other rule, except@charsetand@layerstatements. This is why the order statement can sit above the imports. If you put a@layerblock before an@import, the import is ignored.- Writing
layer(vendor)creates the layer if it doesn't exist. If the order statement already named it, the import joins the existing slot in that order. - Without an order statement, layers take their order from first appearance. The imports then define the order by their position, which is easy to break later. Always write the order statement first.
You can combine layer() with supports() and a media query. The order is fixed: the layer, then supports(), then the media list.
@import url("print-theme.css") layer(vendor) supports(display: grid) print;Loading without `@import`
A <link> element has no attribute for layers. You have three options:
- Use
@import ... layer(...)in a stylesheet or in a<style>element. - Wrap the vendor code in
@layer vendor { ... }at build time. Bundlers and PostCSS plugins can do this. - Import the file from your own entry CSS and let the bundler inline it.
<style>
@layer vendor, site;
@import url("/css/framework.css") layer(vendor);
</style>
<link rel="stylesheet" href="/css/site.css">The site.css file must put its rules inside @layer site { ... }. If it doesn't, they are unlayered and win over everything normal in vendor, which still works but gives up the ordering between your own layers.
Plain @import loads the file only after the browser has parsed the importing stylesheet, so imports can create a request chain and delay rendering. For production, prefer wrapping at build time, or at least put the imports in the first stylesheet the page loads.
Choosing where the vendor layer goes
The position of the vendor layer decides who wins. The table assumes normal declarations.
| Vendor layer position | Effect | Typical use |
|---|---|---|
| First, before your layers | All your layered and unlayered rules override it | Frameworks you customize |
| After `reset`, before `base` | The vendor layer overrides the reset, and your styles override the vendor layer | Frameworks that expect to build on a reset |
| After your own layers | The vendor layer overrides your rules | Almost never what you want |
| Not in any layer | It beats all your layered rules | Common accident, see below |
A common layout is:
@layer reset, vendor, base, components, utilities;This puts the reset under the vendor code, so the vendor's own opinions about margins and fonts take effect. Your base, components, and utilities can then change anything.
flowchart LRThe flowchart above is only a placeholder for syntax, so ignore it. The real diagram follows.
What can still beat your layers
Layers contain a stylesheet only when the stylesheet is actually in a layer. These cases escape:
- Unlayered vendor CSS. A framework added with a plain
<link>or an unlayered@importbeats all of your layered rules. Your fix is to layer it, or to move your overrides out of layers. - Injected
<style>elements. Widgets such as chat boxes and consent banners often append unlayered styles at runtime. They beat your layered normal rules. You can't wrap them from outside. Use an unlayered override with a precise selector, or configure the widget to skip its styles. - Inline styles. A
styleattribute set by a script beats any normal layered or unlayered rule. Only!importantin a stylesheet can beat it. !importantin the vendor. See the next section.
The `!important` trap
For !important declarations, the layer order is reversed. The earliest layer wins, and unlayered important declarations come last among important ones. If a framework declares display: none !important in a layer placed first, none of your later layers can override it with !important.
@layer vendor, site;
@layer vendor {
.hidden { display: none !important; }
}
@layer site {
.hidden { display: block !important; } /* loses */
}The element stays hidden. Placing vendor first helps your normal rules, but it helps the vendor's !important rules too. You have three ways to handle this:
- Don't fight vendor
!important. Change the markup or the framework option that produces the class. - If you must win, place
sitebeforevendorfor important declarations. This is only practical if you have few of them, because it also flips every normal declaration. Splitting the vendor code into two layers is the more precise option. - Use
revert-layeror a more specific override at the framework's own level, where you control the framework layer's contents.
Treat any vendor !important as a deliberate API of that framework and check its documentation before overriding it.
Frameworks that already use layers
Some libraries ship with their own @layer blocks. When you import such a file with layer(vendor), the library's layers become nested inside vendor. The library's internal order is kept, and the whole group occupies the single vendor slot in your order.
/* lib.css */
@layer base, components;
@layer base { a { color: blue; } }
@layer components { .card a { color: black; } }/* site.css */
@layer vendor, site;
@import url("lib.css") layer(vendor);The effective layers are vendor.base, vendor.components, and site. Rules in lib's unlayered code become part of vendor itself, and they beat vendor.base and vendor.components, but they are still beaten by site. You can add to one of the library's layers from your own code with dot notation, for example @layer vendor.components { ... }. That reopens the nested layer and puts your rules in the library's slot, which is useful when you want to adjust a component without leaving the library's order.
A short checklist
- Write one order statement at the top of the entry stylesheet.
- Import every third-party file into a named layer, never bare.
- Put the vendor layer before your own layers, but after
resetif the framework relies on one. - Check DevTools for rules that still come from an unlayered source.
- Search the vendor CSS for
!importantbefore you plan to override anything.
Exercise
A page has this stylesheet. The .btn button still shows a blue background from the framework. List two likely causes and a fix for each.
@import url("framework.css") layer(vendor);
@layer vendor, site;
@layer site {
.btn { background: purple; }
}
Show answer
First cause: the @import comes before the @layer vendor, site; statement, which is allowed, but the layer order is set by first appearance. Here vendor appears first through the import, so it is still ahead of site, and ordering is not the problem. The more likely causes are (1) another copy of framework.css is loaded with a plain <link>, which is unlayered and beats site. Fix this by removing the link or importing it into the layer. (2) The framework declares background: blue !important inside vendor. Important declarations reverse layer order, so vendor, the earlier layer, wins. Fix this by not using that framework class, by changing the framework's option that emits the !important, or by moving site before vendor.
Exercise
Write the first lines of a stylesheet that load normalize.css into a reset layer and framework.css into a vendor layer, then give your own rules base, components, and utilities layers, so that utilities wins over everything normal.
Show answer
@layer reset, vendor, base, components, utilities; @import url("normalize.css") layer(reset); @import url("framework.css") layer(vendor); The order statement comes first, the imports follow it before any other rules, and later layers have higher priority for normal declarations.