Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic :last-child in SASS

I've been messing around with SASS for a while and have made some nice functions that makes use of @if @else if etc. However I have the following two pieces of code on a Mixin:

&:last-child { float: right; margin-right: 0; } 
&:only-child { float: left; margin-right: 0; }

This obviously applies both of these pieces of code to every element I include this particular Mixin on. Is there a way of dynamically checking whether an element is a :last-child / :only:child with an @if statement or any other methods?

Something like:

@if :last-child == True { float: right; margin-right:0; }

Hopefully I've explained that well enough.

Thanks

like image 363
Richard Watts Avatar asked Jun 03 '13 13:06

Richard Watts


1 Answers

Sass doesn't know anything about your document. It can't check if the element is the first-child or only-child. Sass can only be used to generate valid CSS.

If you're looking for the last-child that is not an only-child, this is your selector:

&:last-child:not(:only-child) {
    // styles
}

http://tinker.io/1717b

If you're wanting to disable output of one or the other (because you already know that only one of them will be applicable in this instance), then you'll need an extra argument passed to your mixin:

@mixin foo($children: true) {
  @if $children or $children == last-child {
    &:last-child {
      // styles
    }
  }
  @if $children or $children == only-child {
    &:only-child {
      // styles
    }
  }
}
like image 59
cimmanon Avatar answered Nov 15 '22 09:11

cimmanon