Home >Web Front-end >CSS Tutorial >An Introduction to Container Queries in CSS
CSS Container Queries: Revolutionizing Responsive Design
This excerpt from Unleashing the Power of CSS explores the transformative potential of container queries in crafting adaptable and resilient web components. Unlike viewport media queries that react to the entire browser window size, container queries allow styling based on an element's available space, enabling truly component-level responsiveness.
Container Queries vs. Viewport Media Queries
Traditional viewport-based responsive design relies on breakpoints tied to simplified device sizes (mobile, tablet, desktop), often coupled with a layout grid. This approach struggles with individual component adaptability; larger elements might adjust separately, but generally follow the global breakpoints.
Container queries offer a superior solution. The following image demonstrates a card component styled with container queries, completely independent of the viewport size. The card's appearance adapts dynamically to its available space.
Note: Broad browser support for container queries exists since Firefox 110. Polyfills are available for older browsers.
Defining Container Queries
To utilize container queries, first declare an element as a container using the container-type
property. inline-size
(equivalent to width in horizontal writing modes) is the most common and widely supported value:
<code class="language-css">.container { container-type: inline-size; }</code>
Next, employ the @container
at-rule to define the query. The following example sets the h2
color to blue when its container is 40ch wide or larger:
<code class="language-css">@container (min-width: 40ch) { h2 { color: blue; } }</code>
For broader compatibility across writing modes, use logical properties:
<code class="language-css">@container (inline-size > 40ch) { h2 { color: blue; } }</code>
Beyond inline-size
, options include block-size
and aspect-ratio
. Consult the official specification for further details.
Upgrading a Card Component: A Practical Example
Without container queries, card variations would typically involve modifier classes tied to viewport breakpoints. The image below showcases three card sizes and their corresponding classes.
[CodePen Demo: Viewport Media Query Cards](Link to CodePen)
Using container queries, we maintain a default card style (for unsupported browsers) and define additional styles based on container width:
[CodePen Demo: Container Queries for Cards](Link to CodePen)
This excerpt is from Unleashing the Power of CSS: Advanced Techniques for Responsive User Interfaces, available on SitePoint Premium.
Key takeaways:
container-type
and @container
.(Note: Replace "Link to CodePen" with actual CodePen links if available.)
The above is the detailed content of An Introduction to Container Queries in CSS. For more information, please follow other related articles on the PHP Chinese website!