HTML & CSS Interview Question #106

What are container queries?

Responsive Design, Modern CSS, Variables, Transitions & Animations Senior Advanced

Quick Interview Answer

Container queries allow a component to change its styles according to the size or characteristics of a containing element rather than the entire viewport. They are particularly useful for reusable components that may appear in a narrow sidebar or a wide main-content area.

Detailed Explanation

Container queries allow a component to change its styles according to the size or characteristics of a containing element rather than the entire viewport. They are particularly useful for reusable components that may appear in a narrow sidebar or a wide main-content area.

A size query requires an appropriate query container, commonly created with container-type. The component can then use @container rules to adapt to the space actually available to it.

Code Example

.product-region {
    container-type: inline-size;
}

.product-card {
    display: grid;
    gap: 1rem;
}

@container (min-width: 32rem) {
    .product-card {
        grid-template-columns: 10rem 1fr;
    }
}