Day 59: naming container
source link: https://www.matuzo.at/blog/2022/100daysof-day59/
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 59: naming container
posted on December 15., 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.
When you add a container query, it will look for the nearest ancestor container, by default. If you have multiple nested containers or if you just want to make sure that your query uses the right container, you can name containers and query them specifically.
Let's say, we have 2 size containers, .wrapper
and <section>
.
<div class="wrapper">
<section>
<h2>Latest news</h2>
<div class="card">
<h2>Hey, I'm a card!</h2>
</div>
</section>
</div>
/* That's our outer size container. */
.wrapper {
container-type: inline-size;
}
/* That's our inner size container. */
section {
width: 50%;
container-type: inline-size;
}
/* Default styles for the card. */
.card {
background-color: yellow;
border: 5px solid;
}
/* Container query */
@container (min-width: 500px) {
.card {
background-color: hotpink;
}
}
By default, the container query watches the width of the closest size container, <section>
. You grab and resize the <section>
by clicking and dragging it in the bottom right corner. The background color of the .card
changes as soon as the width of the parent section hits 500px
.
Latest news
Hey, I'm a card!
By naming the container and using that name in the query, you can target a specific container.
/* That's our outer size container. */
.wrapper {
container-type: inline-size;
container-name: wrapper;
}
/* That's our inner size container. */
section {
container-type: inline-size;
}
/* The query watches the width of the outer size container (.wrapper) */
@container wrapper (min-width: 500px) {
.card {
background-color: hotpink;
}
}
You grab and resize the .wrapper
by clicking and dragging it in the bottom right corner. The background color of the .card
changes as soon as the width of the .wrapper
is lower than 500px
.
Latest news
Hey, I'm a card!
Further reading
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK