Modern CSS: container queries, :has, layers and nesting
Features that replace JavaScript and old hacks. Check browser support before relying on them.
Container queries
A media query looks at the viewport. A container query looks at the size of a parent, so a component adapts to where it is placed.
.sidebar, .main { container-type: inline-size; }
.card { display: grid; gap: 1rem; }
@container (min-width: 30rem) {
.card { grid-template-columns: 8rem 1fr; }
}:has() the parent selector
/* style a card that contains an image */
.card:has(img) { padding-top: 0; }
/* style a form row when its input is invalid */
.field:has(input:user-invalid) { color: #b91c1c; }Cascade layers
@layer reset, base, components, utilities;
@layer components { .btn { padding: .5rem 1rem; } }
@layer utilities { .p-0 { padding: 0; } } /* wins, regardless of specificity */Layers listed later win over earlier ones before specificity is considered. They tame third-party CSS and make overrides predictable.
Native nesting
.nav {
display: flex;
a { padding: .5rem; }
a:hover { background: var(--accent); }
@media (max-width: 40rem) { flex-direction: column; }
}CarefulCheck support on caniuse.com and decide on a fallback (or progressive enhancement) before you depend on a new feature. Use @supports (selector(:has(*))) to apply styles only where it works.
NoteOther useful modern features: clamp() for fluid type (font-size: clamp(1rem, 2.5vw, 1.5rem)), aspect-ratio, logical properties (margin-inline) and color-mix().
Test yourself
Answer all the questions, then check them. Finish with every answer right to mark the lesson as done.