Modern CSS Features You Can Use Today Without JavaScript
Container queries, :has(), native nesting, clamp(), aspect-ratio, and view transitions: modern CSS that replaces code you used to write in JavaScript.
By UndieGravity, , 1 min read
CSS has gained features that used to need JavaScript or a preprocessor. The ones below work in all current major browsers, so you can use them in production.
Container queries
Media queries react to the screen. Container queries react to the space a component actually has, so the same card can be compact in a sidebar and wide in the main column.
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 480px) {
.card {
display: grid;
grid-template-columns: 160px 1fr;
}
}The :has() selector
:has() styles an element based on what it contains, sometimes called a parent selector.
/* Highlight a form field row when its input is invalid */
.field:has(input:user-invalid) {
border-color: #d92d20;
}
/* Cards with an image get a different layout */
.card:has(img) {
grid-template-rows: auto 1fr;
}Native nesting
.button {
background: #3f3cf2;
color: white;
&:hover {
background: #322fc9;
}
& svg {
width: 1rem;
}
}Plain CSS now supports nesting, which was the main reason many projects used Sass.
Fluid sizes with clamp()
h1 {
font-size: clamp(2rem, 1.2rem + 3vw, 3.5rem);
}The heading grows with the screen but never goes below 2rem or above 3.5rem. One line replaces several media queries.
aspect-ratio
aspect-ratio: 16 / 9 reserves the right space for a video or image before it loads, which prevents layout shift.
View transitions
The View Transitions API animates between two states of a page, or between pages, with a cross-fade by default. For multi-page sites, adding @view-transition { navigation: auto; } to both pages enables animated navigation in supporting browsers, and other browsers simply navigate normally.
Respect reduced motion
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}Some visitors get dizzy from motion. This rule respects the setting in their operating system.