Sub topic 2
Size Conditions, Range Syntax, and Container Matching
Assume you know CSS selectors, the box model, flexbox or grid, and basic @media queries. A container query tests an ancestor’s size, so a component can respond to the space available to it rather than to the viewport.
Size conditions and logical operators
Declare an eligible query container with container-type. inline-size enables queries on the container’s inline axis, usually its width. Use size when you also need to query its height.
.card-wrapper {
container-type: inline-size;
}
.card {
display: block;
}
@container (min-width: 400px) {
.card {
display: grid;
grid-template-columns: 8rem 1fr;
gap: 1rem;
}
}
@container (400px <= width <= 700px) {
.card {
padding: 1.5rem;
}
}
@container (width > 700px) or (height > 500px) {
.card {
padding: 2rem;
}
}
@container not (width < 400px) {
.card h2 {
font-size: 1.5rem;
}
}Range syntax expresses a lower and upper bound in one condition. Combine conditions with and, or, and not. A height condition requires container-type: size; inline-size alone does not provide queryable height.
Naming containers
Use a name when several containers could match or when the relationship should be explicit. The container shorthand sets both the name and type.
.sidebar {
container: sidebar / inline-size;
}
@container sidebar (width > 30rem) {
.widget {
flex-direction: row;
}
}Which container does a query match?
An unnamed query searches outward from the queried element and uses the nearest eligible ancestor. A named query searches outward for the nearest eligible ancestor with that name. The matching container must be an ancestor, not a sibling or the element being styled.
What containment changes
container-type applies containment. The browser treats the container’s contents as independent for the relevant sizing calculations. This prevents circular queries, but it can change intrinsic sizing and available space. Check flex and grid behavior when a container suddenly becomes narrower or collapses unexpectedly.
Exercise
Why does @container (height > 500px) fail when the ancestor uses container-type: inline-size?
Show answer
inline-size enables queries on the inline axis only. Use container-type: size when the query must inspect both width and height.