badallen
badallen

Reputation: 1127

Nesting objects in SASS

In Sass, if I have a code like this

div.myPanel {
.btn button, .toolbar { td, span { font-size: 9px; } } }

I get something like this

div.myPanel .btn button td, div.myPanel .btn button span, div.myPanel .toolbar td, div.myPanel .toolbar span { font-size: 9px; }

But in reality, I want

div.myPanel .btn button, div.myPanel .toolbar td, div.myPanel .toolbar span { font-size: 9px; }

Is there any better way for me to reduce the duplicate code like this

div.myPanel

{
.btn button { font-size: 9px; }

.toolbar
{
    td, span
    {
        font-size: 9px;
    }
}

}

Upvotes: 0

Views: 769

Answers (1)

David Kaneda
David Kaneda

Reputation: 5490

I would suggest a minor tweak to your second form, including the .toolbar selector twice, so you're only writing the actual rule once:

div.myPanel {
  .btn button, .toolbar td, .toolbar span {
    font-size: 9px;
  }
}

For more in depth cases of this, you should check out @extend. Basically, if you have a class that is like:

.base9 { font-size: 9px; }

You would then convert your second example above to something like this, but note the editable style is still in one rule:

div.myPanel {
  .btn button {
    @extend .base9;
  }
  .toolbar {
    td, span {
      @extend .base9;
    }
  }
}

#someUnrelatedElement small {
  @extend .base9;
}

Extend works by simply collapsing the selectors into one rule (like you're looking for), so it's great for performance in cases like this.

Upvotes: 2

Related Questions