Generic Sass Placeholder Mixin & Function Pair

Why?

The idea of this @mixin-@function pair is to take the work that Sam Richards covered in the alistapart article ' DRY-ing out Your Sass Mixins ' and just neaten the edges so @mixins look tidier... ( I just found them to look a little unweildly :S ). Read the article. It's all kinds of clever stuff.

How this works...

First create the generic parts to this mixin-function pair. This only needs to be done once can live in a function scss file and never be touched again!

First we create a placeholder map that holds all our placeholder keys, e.g. button, clearfix, whatever. Then we make a @mixin that will check for an existing key and if it exists it will do nothing. If it doesn't then it creates a unique placeholder class, saves it to the map for later use and then fills the placeholder with anything passed to the @mixin via { } and @content.

The Third stage is simply a lookup for a given key and it returns the right selector. You are in charge here as it doesnt and can't do error checking. This should only ever be run after the maker has done it's business for that key as we shall see shortly.

    // - 1
    $Placeholder-Selectors: (); 
    
    // - 2
    @mixin testPlaceholderForKey($key) {
  $selector: map-get($Placeholder-Selectors, $key);  
  @if $selector == null { //if no key is set
    $selector: unique-id(); //make a unique class string    
    $Placeholder-Selectors: map-merge($Placeholder-Selectors, ($key: $selector)) !global;
    @at-root %#{$selector} {
       @content; 
    }
  }
    }
    
    // - 3
    @function getPlaceholderForKey($key) {
  $selector: map-get($Placeholder-Selectors, $key);
  @return $selector;
    }

Now the specific mixin can be created. In the clearfix example we first test for the key of 'clearfix' and pass it the code to use when it creates the clearfix placeholder.

Stage 2 is simple a check for the selector and can extend the placeholder.


  @mixin cf() {
  // - 1
  @include testPlaceholderForKey('clearfix') {
    &:after {
      visibility: hidden;
      display: block;
      font-size: 0;
      content: " ";
      clear: both;
      height: 0;
    }
  }
  // 2
  @extend %#{getPlaceholderForKey('clearfix')};
  }
  

We can then just call the @mixin when we need and it will take care of the rest

    .wrapper {
	@include cf();
    }
  

Testing with clearfix();

Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item
Item

Testing with button();

I am a button I am also a button

Testing with innerMixin();

OMG WOW