The @container CSS at-rule - container queries
With container queries you can query the styling information of a parent element, such as its inline-size. With media queries, you could query the size of the viewport, container queries enable components that can change based on where they are in the UI.
Container queries are especially handy for responsive design and reusable components.Container queries are especially handy for responsive design and reusable components.
To use container queries, you need to declare a containment context on an element To do this, use the container-type property with a value of size, inline-size, or normal.
.post {
container-type: inline-size;
}
Next, use the @container at-rule to define a container query.
/* Default heading styles for the card title */
.card h2 {
font-size: 1em;
}
/* If the container is larger than 700px */
@container (min-width: 700px) {
.card h2 {
font-size: 2em;
}
}
Naming containment contexts
It’s possible to give a containment context a name using the container-name property.
.post {
container-type: inline-size;
container-name: sidebar;
}
@container sidebar (min-width: 700px) {
.card {
font-size: 2em;
}
}
Shorthand container syntax
.post {
container: sidebar / inline-size;
}
Container query length units
- cqw: 1% of a query container’s width
- cqh: 1% of a query container’s height
- cqi: 1% of a query container’s inline size
- cqb: 1% of a query container’s block size
- cqmin: The smaller value of either cqi or cqb
- cqmax: The larger value of either cqi or cqb
@container (min-width: 700px) {
.card h2 {
font-size: max(1.5em, 1.23em + 2cqi);
}
}
Logical keywords in container queries
- and combines two or more conditions.
- or combines two or more conditions.
- not negates the condition. Only one ‘not’ condition is allowed per container query and cannot be used with the and or or keywords.
@container (width > 400px) and (height > 400px) {
/* <stylesheet> */
}
@container (width > 400px) or (height > 400px) {
/* <stylesheet> */
}
@container not (width < 400px) {
/* <stylesheet> */
}