@container is a modern CSS feature used to create responsive components based on the size of their parent container instead of the full viewport size.
Traditional responsive design uses:
[code theme="dark"]
@media
[/code]
which depends on screen size.
But @container allows components to respond according to their own container width.
Why @container is Important
- Creates truly reusable components
- Better responsive layouts
- Works inside dynamic layouts
- Perfect for cards and widgets
- Improves component-based design systems
- More flexible than media queries
Difference Between @media and @container
|
Feature
|
@media
|
@container
|
|
Based On
|
Viewport size
|
Parent container size
|
|
Best For
|
Page layouts
|
Reusable components
|
|
Flexibility
|
Limited
|
Very High
|
Basic Syntax
[code theme="dark"]
.container{
container-type:inline-size;
}
@container (min-width:500px){
.card{
display:flex;
}
}
[/code]
How @container Works
First, define a container using:
[code theme="dark"]
container-type:inline-size;
[/code]
Then use:
[code theme="dark"]
@container
[/code]
to apply styles based on the container width.
Simple Card Example
[code theme="dark"]
[/code]
[code theme="dark"]
.wrapper{
container-type:inline-size;
}
.card{
padding:20px;
background:#f3f4f6;
}
@container (min-width:600px){
.card{
display:flex;
gap:20px;
}
}
[/code]
When the wrapper becomes wider than 600px, the card layout changes automatically.
[grid]
CSS Container Query Example
Responsive Card Using @container
Modern Component-Based Layout
Container Query Responsive Demo
[/grid]
container-type Values
|
Value
|
Description
|
|
inline-size
|
Tracks width changes
|
|
size
|
Tracks width and height
|
Named Containers
[code theme="dark"]
.wrapper{
container-name:cardLayout;
container-type:inline-size;
}
@container cardLayout (min-width:500px){
.card{
display:grid;
}
}
[/code]
Named containers help target specific containers in large applications.
Advantages of @container
- More flexible responsive design
- Reusable responsive components
- Better design systems
- Cleaner component architecture
- Modern responsive workflow
Disadvantages of @container
- Newer feature for many developers
- Requires modern browser support
- Can become complex in large layouts
Best Use Cases
- Reusable cards
- Dashboard widgets
- Component libraries
- Modern design systems
- Nested responsive layouts
Cross Browser Compatibility
- Chrome → Supported
- Edge → Supported
- Firefox → Supported
- Safari → Supported
- Mobile Browsers → Good Support
@container is now supported in all major modern browsers.
Older browsers may not support container queries fully.
Browser Support Summary
[code theme="dark"]
@container (min-width:600px){
.card{
display:flex;
}
}
[/code]
is considered one of the most important modern CSS responsive features for component-based UI development.