Container Queries
Container queries enable responsive design based on container size rather than viewport size, allowing for more modular and reusable components.
Overview
Container queries provide a way to style elements based on their container's size, rather than the viewport size. This enables truly modular design where components can adapt to their available space regardless of screen size.
Feature | Description |
---|---|
Container Types | inline-size, size |
Named Containers | main, sidebar, card, section |
Query Types | up, down, between, only |
Basic Usage
Enable container queries on an element and style its children based on the container's size:
Container Types
Two container types are available through utility classes:
Class | Property | Description |
---|---|---|
.container-inline-size | container-type: inline-size; | Queries based on inline axis (width) |
.container-size | container-type: size; | Queries based on both width and height |
Query Mixins
Various mixins are available for different query patterns:
Mixin | Description | Example |
---|---|---|
container-up($breakpoint) | Styles for containers larger than breakpoint | @include container-up('md') |
container-down($breakpoint) | Styles for containers smaller than breakpoint | @include container-down('lg') |
container-between($lower, $upper) | Styles for containers between breakpoints | @include container-between('sm', 'lg') |
container-only($breakpoint) | Styles for specific breakpoint range | @include container-only('md') |
container-query($size) | Custom size queries | @include container-query('400px') |
Named Containers
Predefined container names are available through utility classes:
Practical Examples
Responsive Card Layout
Adaptive Sidebar
Container Utility Mixins
The framework provides core mixins for defining container properties:
Best Practices
Do
- Use container queries for component-level responsiveness
- Name containers semantically
- Combine with media queries when appropriate
- Consider performance impact of nested containers
- Use inline-size when only width matters
Avoid
- Creating unnecessary containment contexts
- Deep nesting of container queries
- Using size when inline-size would suffice
- Querying containers without clear boundaries
- Overcomplicating layouts with too many queries