Quick Tip: Nest Related Properties for More Readable CSS

I sort CSS properties alphabetically. That’s my preference. I like that I don’t need to think about it — plugins do the actual work of sorting for me — and things are always where I expect them. The most obvious downside is that often related and/or dependent properties are not defined together.

Take this full-screen overlay, for instance:

.overlay {
bottom: 0;
left: 0;
overflow: auto;
position: fixed;
right: 0;
top: 0;
z-index: 9000;
}

Not bad, but let’s add some more styling:

.overlay {
animation: overlay-in 0.2s;
animation-fill-mode: forwards; /* must come after 'animation' */
animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);
background-color: #fff;
bottom: 0;
left: 0;
opacity: 0;
overflow: auto;
padding: 1rem;
position: fixed;
right: 0;
top: 0;
transform: scale(0.5) translateY(10%);
will-change: opacity, transform;
z-index: 9000;
}

Oh boy. You’d have to take in this whole block just to figure out what’s going on with positioning. We can use nesting (no, not that nesting) to tidy it up:

.overlay {
animation: overlay-in;
animation-duration: 0.2s;
animation-fill-mode: forwards;
animation-timing-function: cubic-bezier(0.23, 1, 0.32, 1);
background-color: #fff;
opacity: 0;
overflow: auto;
padding: 1rem;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
transform:
scale(0.5)
translateY(10%);
will-change: opacity, transform;
z-index: 9000;
}

Nice.