Search code examples
sasspseudo-class

Custom directives within scss files? Perhaps for a new pseudo class?


Is it be possible to use some sort of @directive creation syntax, similar to creating @mixins? Secondly, is it possible to create a SASS-only pseudo class?

I'd like to declare my own SASS directive,although I'd prefer not to have to force my teammates to install an extra ruby gem to use it so I'd want to store it in a scss partial. I do understand that they are orders of levels in complexity, so perhaps it just isn't possible.

In addition to perhaps creating a new scss-only pseudo class (such as :parent, :clicked, :unchecked, etc) I'd be interested in a custom-made directive that assists with using checkboxes to direct css animations ("css checkbox hack"). Here is my scss pseudocode to generalize what I'm trying to do:

//  this code monitors when a checkbox (#someinput) is checked,
//  then applies style to div #target div.  Basically an 'onClick' event in scss.
body {
  #wrapper {
    #targetdiv {
      @spotcheck(#someinput) {                 #
        color: red; border: 2px solid blue;    # <-- move this ...
      }                                        #

      color: blue; border: 0;
      #someinput {
        width: 20px; height: 20px;
      }
    }
  }
}

// ... the above scss should be converted to this pre-compiled state, also scss
body {
  #someinput:checked ~ #targetdiv {           #
    color: red; border: 2px solid blue;       # <-- ..to here. it needs to be 
  }                                           #       above the #targetdiv

  #wrapper {
    #targetdiv {
      color: blue; border: 0;
      #someinput {
        width: 20px; height: 20px;
      }
    }
  }
}

Solution

  • Make your selectors only as specific as they absolutely need to be and no more. A mixin would only be more verbose with no real benefit.

    #targetdiv {
        color: blue; border: 0;
    
        #someinput:checked ~ & {
            color: red; border: 2px solid blue;
        }
    }
    
    #someinput {
        width: 20px; height: 20px;
    }
    

    Output:

    #targetdiv {
      color: blue;
      border: 0;
    }
    #someinput:checked ~ #targetdiv {
      color: red;
      border: 2px solid blue;
    }
    
    #someinput {
      width: 20px;
      height: 20px;
    }
    

    Alternately, this would give the same result with the ability to overqualify as much as you want:

    #targetdiv {
        color: blue; border: 0;
    }
    
    #someinput {
        width: 20px; height: 20px;
    
        ~ #targetdiv {
            color: red; border: 2px solid blue;
        }
    }