Day 80: container style queries
source link: https://www.matuzo.at/blog/2023/100daysof-day80/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Day 80: container style queries
posted on January 13., 2023
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.
Container style queries allow querying the computed values of a query container.
No browser supports it yet, but we should be able to do something like this:
.card {
aspect-ratio: 1 / 1;
}
.card--wide {
aspect-ratio: 16 / 9
}
@container style(aspect-ratio: 16 / 9) {
img {
object-fit: cover;
}
}
We can check whether a container has a specific property and value assigned and apply additional styles based on this condition. Chrome support container style queries behind a flag, but only with custom properties, not ordinary properties.
Here’s an example based on a component I've built a while ago where this can be useful. We have a card component that can be used in different ways. It can contain just text, text and an image, text and a video, and also text with a background color. Most background colors in our design system work well with black as the text color, but there’s one exception.
:root {
--nebelgrau: #d6d1ca;
--flieder: #aaaafa;
--abendstimmung: #49274b;
}
.card {
--bg: var(--nebelgrau);
background-color: var(--bg);
}
<div class="card">
<h2>Chapter 1</h2>
</div>
<div class="card" style="--bg: var(--flieder)">
<h2>Chapter 2</h2>
</div>
<div class="card" style="--bg: var(--abendstimmung)">
<h2>Chapter 3</h2>
</div>
Chapter 1
Chapter 2
Chapter 3
I could assign a class to this specific card variation and just change the text color. That’s actually what we’re doing at the moment, but with style queries I can create a general rule that changes the text color whenever the container has a specific background color.
@container style(--bg: var(--abendstimmung)) {
* {
color: #fff;
}
}
Chapter 2
Further reading
Want more?
Overview: 100 Days Of More Or Less Modern CSS
My blog doesn't support comments yet, but you can reply via e-mail.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK