Global Styles
Add global to a style tag and its rules are left exactly as you
wrote them - no hash class, no scoping, no limits:
<style global>
body {
font-family: system-ui;
margin: 0;
}
a {
color: blue;
}
</style>
A component can have both kinds of block.
Reach for the global one when the rule has to leave the component, which in
practice means one of four things: base styles and resets, theme variables on
:root, styling markup passed into a <slot />,
or overriding a third-party stylesheet.
<!-- Card.html -->
<div class="card">
<slot />
</div>
<style>
/* Scoped: this component's .card, and nothing else's */
.card {
border: 1px solid #ccc;
padding: 1rem;
}
</style>
<style global>
/* Global: reaches the markup the page passed in */
.card h2 {
margin: 0 0 0.5rem;
}
</style>Scoped .card matches only this component's card.
Global .card h2 matches any h2 inside any
.card on the page - including the heading the page passed into
the slot, which the scoped block cannot see.
.card h2 rule
now applies to every .card in the app, whoever wrote it. Keep
global blocks small, and give their selectors names you own.
When the rules arrive
A component's CSS goes on the page the first time that component mounts, and identical blocks are only added once however many copies you render.
Blocks land in mount order, so a later component's global rule can override an earlier one at equal specificity.
Styles that must be there before anything paints - a reset, your theme
variables - belong in your root layout.html, which mounts first.
:global(...). If you have written
Svelte or Vue, the per-selector escape hatch does not exist here. JAF's
scoper would append its hash to it and the browser would drop the whole
rule. Use a separate <style global> block instead.
Related
- Scoped Styles - the default, and what it cannot reach
- CSS Variables - the usual reason for a global block