Day 85: typed custom properties in container style queries
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.
Registering typed custom properties can be useful in container style queries.
The following container style query matches because the computed value of both --bg
and --color
is “red”.
html {
--color: red;
}
.card {
--bg: red;
}
/* Condition is true, styles applied */
@container style(--bg: var(--keyword)) {
h1 {
border: 10px dotted fuchsia;
}
}
What's important to understand is that we're comparing two strings, not colors. If we change --color
to rgb(255 0 0)
, the query doesn't match anymore.
html {
--color: rgb(255 0 0);
}
.card {
--bg: red;
}
/* Condition is false, styles not applied */
@container style(--bg: var(--color)) {
h1 {
border: 10px dotted fuchsia;
}
}
That's where the @property
rule comes into play. It allows us to add a type to a custom property and turn --bg
into a proper color value.
@property --bg {
syntax: '<color>';
inherits: true;
initial-value: rgb(0 0 0);
}
html {
--color: rgb(255 0 0);
}
.card {
--bg: red;
}
/* Condition is true, styles applied */
@container style(--bg: var(--color)) {
h1 {
border: 10px dotted fuchsia;
}
}
As you can see, you only have to add a type to --bg
and not --color
, as well. That's because --bg
is resolved as a color in both the declaration in .card
and in the query.
Further reading
Overview: 100 Days Of More Or Less Modern CSS