Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access the parent selector from within a SASS mixin

I have set up a mixin for a button using display:inline-block. I am trying to get to the parent of whatever class that will eventually end up using the mixim, so I can add the font-size: 0px line there to make sure that I don't need to make adjustments to my HTML to avoid unwanted space between each button.

Here's an example... I want the. parent class to receive the font-size: 0px line.

@mixin button() {
    display:inline-block;
    font-size: 1em;
    //other stuff to make a pretty button
    && { font-size: 0px; }
}

.parent{
    .child {
        @include button();
    }
}
like image 568
MacBryce Avatar asked Apr 22 '13 15:04

MacBryce


People also ask

How do I reference a parent selector in Sass?

The parent selector, & , is a special selector invented by Sass that's used in nested selectors to refer to the outer selector. It makes it possible to re-use the outer selector in more complex ways, like adding a pseudo-class or adding a selector before the parent.

Can I use a mixin inside a mixin?

As mentioned in the other answers, you can include mixins in other mixins. In addition, you can scope your mixins. Scoping mixins means that you can have multiple mixins named the same in different scopes without conflicts arising.

Is it possible to select a parent element in CSS?

Definition and UsageThe element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.


1 Answers

As of Sass 3.4 this is now possible.

@mixin parent {

  @each $selector in & {

    $l: length($selector);

    @if ($l == 1) {
      @error "Used parent mixin on a top-level selector";
    } @else {

      $parent: nth($selector,1);
      @for $i from 2 to $l {
        $parent: append($parent,nth($selector,$i));
      }

      @at-root #{$parent} {
        @content;
      }

    }
  }
}

// Use
.grandparent {
  .parent{
      .child {
        font-size: 1em;
          @include parent {
            font-size: 0px;
          }
      }
  }
}

// Result
.grandparent .parent .child {
  font-size: 1em;
}
.grandparent .parent {
  font-size: 0px;
}

// Errors:
.root {
  @include parent {
    content: "Won't work";
  }
}
.grandparent .parent, .root {
  @include parent {
    content: "Also won't work";
  }
}
like image 139
Karol Tomoki Yamazaki Avatar answered Oct 03 '22 23:10

Karol Tomoki Yamazaki