
Traditionally, we use CSS @media
query to control the responsiveness of the element based on the viewport size (browser’s size).
for example:
@media screen and (max-width: 600px) {
.example {
/*when viewport size <= 600px; use this css*/
}
}
Introducing CSS @container
Query
With the help of the new CSS @container
query, the CSS @container
provides a solution for the children’s elements to control their’s CSS style response toward the dedicated reference’s container.
Attribute | Description |
---|---|
container-type | size, inline-size, normal |
container-name | define a container name to use in @container |
container | A shorthand CSS property to set container-type & container-name . |
To use CSS @container
,
/*establish @container*/
.sample_container {
container-type: inline-size;
container-name: containerName;
}
/*Define @container query:
when .sample_container width is <=600px;
use below CSS*/
@container containerName (max-width: 600px) {
.inner_containerA,
.inner_containerB{
background: yellow;
}
}
- First, you need to establish a reference container by adding
container-type
to the targeted parent element. (line 3) - You can also add in a
container-name
to distinguish just the targeted container (line 4) - Lastly, you can now define the style rules for the targeted
@container
(line 10)
Example:
<!DOCTYPE html>
<html>
<head>
<style>
.sample_main{
display: flex;
}
.sample_sidebar{
width: 20%;
height: 200px;
background: orange;
}
.sample_container {
width: 80%;
/*establish @container*/
container-type: inline-size;
container-name: containerName;
}
.inner_containerA,
.inner_containerB{
background: green;
width: 100%;
height: 100px;
border: 2px solid black;
box-sizing: border-box;
}
/*when container size for ".sample_container"
is <=600px; use below CSS*/
@container containerName (max-width: 600px) {
.inner_containerA,
.inner_containerB{
background: yellow;
}
}
</style>
</head>
<body>
<div class="sample_main">
<div class="sample_sidebar"></div>
<div class="sample_container">
<div class="inner_containerA">
Inner Container A
</div>
<div class="inner_containerB">
Inner Container B
</div>
</div>
</div>
</body>
</html>
Result:

In this example:
- Originally,
.inner_containerA
and.inner_containerB
are set to green background. - By using CSS media query
@container containerName (max-width: 600px)
, when container size for “.sample_container
” is <=600px, set.inner_containerA
and.inner_containerB
background color to yellow
Leave a Reply