Skip to content

Instantly share code, notes, and snippets.

@danielguillan
Created July 16, 2014 11:54
Show Gist options
  • Save danielguillan/2965a959cdfdc7a7bad2 to your computer and use it in GitHub Desktop.
Save danielguillan/2965a959cdfdc7a7bad2 to your computer and use it in GitHub Desktop.
Generated by SassMeister.com.
// ----
// Sass (v3.4.0.rc.1)
// Compass (v1.0.0.alpha.20)
// ----
// -----------------------------------------------------------------------------
// Parent
// -----------------------------------------------------------------------------
/**
* Modifies the context of a selector by adding a user-defined class or
* pseudo-class to its parent component
* Useful for adding classes or pseudo-classes to the parent element
* while avoiding nesting and selector repetition.
*
* @author Daniel Guillan @danielguillan
*
* @throws No selector found
* @throws #{&} has no parent selectors
*
* @todo Might break with more complex selectors. Test and improve.
* @todo Create a context mixin where parent() and base() are aliases for it
*
*/
@mixin parent($class) {
@if (& == null) {
@error 'No selector found';
}
@if (length(nth(&, 1)) < 2) {
@error '#{&} has no parent selectors';
}
$parent: nth(nth(&, 1), -2);
$new-selector: selector-replace(&, $parent, '#{$parent}#{$class}');
@at-root #{$new-selector} {
@content;
}
}
// -----------------------------------------------------------------------------
// Example
// -----------------------------------------------------------------------------
// Old way. Note the selector repetition.
// .parent {
// color: blue;
// &:hover {
// color: red;
//
// .child {
// display: block;
// }
//
// }
//
// &.is-active {
// color: green;
//
// .child {
// color: red;
// }
// }
//
// .child {
// display: none;
// }
//
// }
// New way. Everything in its right place.
.parent {
color: blue;
&:hover {
color: red;
}
&.is-active {
color: green;
}
.child {
display: none;
@include parent(':hover') {
display: block;
}
@include parent('.is-active') {
color: red;
}
}
}
/**
* Modifies the context of a selector by adding a user-defined class or
* pseudo-class to its parent component
* Useful for adding classes or pseudo-classes to the parent element
* while avoiding nesting and selector repetition.
*
* @author Daniel Guillan @danielguillan
*
* @throws No selector found
* @throws has no parent selectors
*
* @todo Might break with more complex selectors. Test and improve.
* @todo Create a context mixin where parent() and base() are aliases for it
*
*/
.parent {
color: blue;
}
.parent:hover {
color: red;
}
.parent.is-active {
color: green;
}
.parent .child {
display: none;
}
.parent:hover .child {
display: block;
}
.parent.is-active .child {
color: red;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment