Nested Property Declarations in Sass

  • SCSS
  • Sass
  • CSS

I have been on an absolute tear at work, cleaning up all kinds of legacy code, addressing large swaths of technical debt, deduping our utility CSS libraries, that kind of thing. It's been a ton of fun and a wonderful learning experience as I wade about knee-deep in Sass/SCSS. It's what inspired last month's blog post, and today's post is a short and sweet continuation of that focus. I'll be writing about something that is probably a basic Sass feature to seasoned frontend/Sass devs, but I haven't run across it myself before, and I thought it was pretty neat. This feature is nested property declarations - basically, the ability to group CSS properties that share a common prefix.

Say you have a headline class that you want to apply to a heading:

<h2 class="headline">About me</h2>

This headline class should apply some basic styles to that heading, perhaps some color, font size, typeface, font weight, that kind of thing. Your desired CSS might look like:

.headline {  color: blue;  line-height: 1.5;  font-family: Georgia, serif;  font-size: 36px;  font-style: italic;  font-weight: 700;}

Sass lets you clean this up a little bit by allowing you nest CSS properties under a font property name. With this in place, it will adding and hyphenate that outer property name to the inner property name. Here's what the sass looks like:

.headline {  color: blue;  line-height: 1.5;  font: {    family: Georgia, serif;    size: 36px;    style: italic;    weight: 700;  }}

And sure enough, this compiles to the CSS we desire:

.headline {  color: blue;  line-height: 1.5;  font-family: Georgia, serif;  font-size: 36px;  font-style: italic;  font-weight: 700;}

Shorthand CSS properties

Of course, shorthand CSS properties factor into this too. Something like margin: 20px auto 16px; is shorthand for:

margin-top: 20px;margin-right: auto;margin-bottom: 16px;margin-left: auto;

You can still embrace the nested property declarations pattern in Sass by passing that outer property name a sort of default or fallback value, and defining explicit values within the inner properies:

.body {  margin: auto {    top: 20px;    bottom: 16px;  }}

This compiles to:

.body {  margin: auto;  margin-top: 20px;  margin-bottom: 16px;}

That's all I have for today. This is pretty basic and simple, but I think it's also a cool and powerful way to group similar styling concerns within a Sass stylesheet.