Skip to content

Instantly share code, notes, and snippets.

@dalgard
Last active February 16, 2016 21:45
Show Gist options
  • Save dalgard/fcb3fa60ed10ef1e9a27 to your computer and use it in GitHub Desktop.
Save dalgard/fcb3fa60ed10ef1e9a27 to your computer and use it in GitHub Desktop.
Sass mixin to help put 'the checkbox hack' (which I rather consider a 'technique') to good use. This version requires a media mixin, e.g. from Neat
@mixin toggled($selector, $media...) {
#{unquote($selector)}:checked ~ & {
@if length($media) > 0 {
@include media($media...) {
@content;
}
}
@else {
@content;
}
}
}
@mixin untoggled($selector, $media...) {
#{unquote($selector)}:not(:checked) ~ & {
@if length($media) > 0 {
@include media($media...) {
@content;
}
}
@else {
@content;
}
}
}
@dalgard
Copy link
Author

dalgard commented Aug 29, 2014

With a few other nice techniques, the mixin can be used like this:

<input type="checkbox" class="hidden" id="mother-toggler">

<main>
  <label class="button only-on-mobile" for="mother-toggler">Toggle punk</label>

  <aside class="punk">Go on, toggle me, see if I care (except on mobile, uff!)</aside>
</main>
.punk {
  color: darkslategray;

  main > & {
    @include toggled('#mother-toggler', $mobile) {
      color: peachpuff;
    }
  }
}

When the element is nested, like in the HTML above, the @include toggled statement has to go inside the full path of the element in relation to the actual checkbox – like above – since the compiled selector has to look like this to work:

#mother-toggler:checked ~ main > .punk

Of course, the toggle may be something less silly/more useful – such as this:

.punk {
  main > & {
    @include media($mobile) {
      display: none;
    }

    @include toggled('#mother-toggler', $mobile) {
      display: block;
    }
  }
}

... which would output something like this:

@media screen and (max-width: 659px) {
  main > .punk {
    display: none;
  }
}
@media screen and (max-width: 659px) {
  #mother-toggler:checked ~ main > .punk {
    display: block;
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment