CSS2 min read
CSS Container Queries Are Here
Responsive components based on parent size, not viewport
S
Shahar Amir
CSS Container Queries Are Here
Media queries respond to viewport size. But what if you want components to respond to their container size?
Now you can.
The Problem
css
1234
/* This card looks different based on VIEWPORT */@media (min-width: 768px) { .card { flex-direction: row; }}But the same card in a sidebar should stay vertical even on wide screens.
Container Queries Solution
css
123456789101112
/* Define a container */.card-wrapper { container-type: inline-size; container-name: card;}
/* Query the CONTAINER size */@container card (min-width: 400px) { .card { flex-direction: row; }}Now the card layout depends on its container, not the viewport!
Basic Setup
css
1234567891011
/* Make an element a container */.sidebar { container-type: inline-size;}
/* Query it */@container (min-width: 300px) { .widget { font-size: 1.2rem; }}Container Types
css
12345678
/* Width queries only (most common) */container-type: inline-size;
/* Width and height queries */container-type: size;
/* No queries, just naming */container-type: normal;Named Containers
css
1234567891011121314
.main { container-name: main; container-type: inline-size;}
.sidebar { container-name: sidebar; container-type: inline-size;}
/* Target specific container */@container sidebar (max-width: 250px) { .nav-link span { display: none; }}Shorthand
css
1234
/* container: name / type */.wrapper { container: card / inline-size;}Container Query Units
New units based on container size:
css
123
.card-title { font-size: 5cqi; /* 5% of container inline size */}cqw— container query widthcqh— container query heightcqi— container inline sizecqb— container block size
Browser Support
Supported in all modern browsers. Finally, truly reusable components!
#responsive#layout#modern-css
Stay Updated 📬
Get the latest tips and tutorials delivered to your inbox. No spam, unsubscribe anytime.