Variable sass self/child selector

in code


I had a problem: I had a mixin. This mixin had a payload of rules that I wanted to pass to the selector that called the mixin. Sometimes, however, I wanted to send the code to a given child selector instead. I played around with variations on Sassmeister until I came up with a mixin guided by a blog post by Guild Hernandez. I realize this sounds dumb, but I didn’t understand that the self selector would resolve to itself if the rest of the selector is null.

My problem was with WordPress menu items. I needed to attach a style to a square span inside of a rectangular hyperlink, but I did not want to rewrite a few hundred lines of code to target it. The menu item looks like this:

<li class="menu-item facebook">
    <a href="#!"><span class="menu-span"></span></a>
</li>

The li is rectangular and the a element is set to fill this. The span I need to be square and sit centered, and it’s precise style to change based on the class of the li. The lowest level of class that WordPress allows you to change via the menu UI is the li.

@mixin selectorer($selector: null) {
    &#{if($selector, ' ' + $selector, $selector)} {
        background: center/100% auto no-repeat url('foo');
    }
}

What I discovered is that &#{$selector} compile to nothing at all if $selector is falsy (null or false), but the code inside will compile as normal.

.ding {
    @include selectorer;
}

.dong {
    @include selectorer('span');
}

becomes

.ding {
  background: center/100% auto no-repeat url("foo");
}

.dong span {
  background: center/100% auto no-repeat url("foo");
}

Today I learned. I have no idea whether this behaviour is intended, but for now it suits me fine.



Decompression

in me


Your email address will not be published. Required fields are marked *