Sitemap

Using @at-root Sass mixin

When long CSS path is annoying you.

1 min readApr 24, 2014

--

A colleague of mine, works on a new website menu trying to handle the active item behavior like so:

<body class="item1">
<ul>
<li class="item1">Item 1</li>
<li class="item2">Item 2</li>
</ul>
</body>

Its first Sass corresponding code was:

ul li
&.item1
color: purple
body.item1 &
font-weight: bold
&.item2
color: green
body.item2 &
font-weight: bold

When he shared its code with me, I was like:

Wow, this looks bad. A BODY tag inside a node element?!?

But it worked well. Even if the idea was pretty smart, the code still was ugly. And I was wondering how we could improve that part in Sass.

@at-root to the rescue

Then I remembered the last new great feature in Sass 3.3: @at-root. And I came back to him with the reusable/readable mixin below:

=in($name)
@at-root #{$name} &
@content

We can now use it like so:

ul li
&.item1
color: purple
+in('body.item1')
font-weight: bold
&.item2
color: green
+in('body.item2')
font-weight: bold

Looks much better! What do you think?

Get Romain Laurent’s stories in your inbox

Join Medium for free to get updates from this writer.

PS: Loosely based on real working life.

--

--