Day 69: width in container queries
source link: https://www.matuzo.at/blog/2022/100daysof-day69/
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 69: width in container queries
posted on December 29., 2022
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.
In a media query, it’s obvious what width means. It always refers to the width of the viewport. With size container queries it’s not that obvious.
/* Kicks in when the viewport has a minimum width of 500px */
@media (min-width: 500px) {
body {
background-color: hotpink;
}
}
width
in a size container query queries the width of the container's content box. Let me illustrate what that means with an example.
The <section>
is the container and the .card
changes background color when the container has a minimum width of 500px.
<section>
<h2>Latest news</h2>
<div class="card">
<h2>Hey, I'm a card!</h2>
</div>
</section>
The <section>
has an explicit width, padding, and a border. It's box-sizing
property is set to the default value content-box
.
section {
box-sizing: content-box;
container-type: inline-size;
width: 500px;
padding: 20px;
border: 10px solid;
}
@container (min-width: 500px) {
.card {
background-color: hotpink;
}
}
The total width of the container (<section>
) is 560px (500px width
+ 40px padding
+ 20px border
). The container query fires when the width without padding and border (content-box
) is at least 500px, not when the total width is 500px.
total width: 560px,
content-box: 500px
Hey, I'm a card!
If you change box-sizing: content-box;
to box-sizing: border-box;
, the total width of the container is 500px (440px width
+ 40px padding
+ 20px border
). The container query still only fires when the content-box is at least 500px.
section {
box-sizing: border-box;
container-type: inline-size;
width: 500px;
padding: 20px;
border: 10px solid;
}
@container (min-width: 500px) {
.card {
background-color: hotpink;
}
}
total width: 500px,
content-box: 440px
Hey, I'm a card!
So, when we talk about width in a size container query, it always refers to the size of the content-box.
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