Container Queries in CSS are a powerful feature that allows styles to be applied based on the size of a parent container rather than the viewport. This makes it possible to create responsive components that adapt to their immediate environment, enhancing modular design and making layouts more flexible and maintainable.
Key Concepts of Container Queries
- Container Query Units (
cqw,cqh,cqi,cqb,cqmin,cqmax): These units are similar to viewport units (vw,vh) but are relative to the size of the container. @containerRule: The@containerrule allows you to specify styles that apply when a container meets certain conditions, such as width, height, or aspect ratio.- Container Type: Before using a container query, the container must be defined with a specific container type:
contain: layout;– Enables layout containment.contain: style;– Enables style containment.contain: size;– Enables size containment.contain: layout style size;orcontain: content;– Enables full containment.
Basic Syntax
- Define the Container:
- First, set the containment type on the parent container:
.parent-container {
contain: layout inline-size; /* Enables layout containment and size query */
/* Other container properties */
}
Write a Container Query:
Use the @container rule to target styles based on the container’s conditions:
@container (min-width: 300px) {
.child-element {
background-color: lightblue;
padding: 20px;
}
}
@container (min-width: 600px) {
.child-element {
background-color: lightcoral;
padding: 40px;
}
}
Benefits of Using Container Queries
- Component-based responsiveness: Styles adapt based on the component’s container rather than the entire viewport, making components more modular.
- Better control and predictability: Perfect for creating reusable, adaptable components that fit various layout contexts.
- Enhanced design flexibility: Enables intricate responsive behaviors within multi-layered designs.