Skip to content

Instantly share code, notes, and snippets.

@mattfreer
Created December 12, 2012 10:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattfreer/4266560 to your computer and use it in GitHub Desktop.
Save mattfreer/4266560 to your computer and use it in GitHub Desktop.
Applies width property to siblings conditionally. Width is applied if the number of siblings matches the supplied sibling-count. This allows developers to set different widths based on the number of siblings. If $sibling-count matches the number-of-siblings then all siblings will be set to an equal percentage width, with a combinded total width …
// @param $sibling-selector: selector to target siblings (e.g. h5 | ".simple-filed")
// @param $sibling-count: the number of siblings that must exist in order for these widths to be applied
// @param $fixed-widths: optional keyword argument, list of fixed (percentage) widths to be applied to
// the first-n siblings (e.g. $fixed-widths: 40 30)
//
// Usage:
// h5 {
// @include width-by-sibling-count(h5, 4, $fixed-widths: 55);
// @include width-by-sibling-count(h5, 5, $fixed-widths: 40);
//}
@mixin width-by-sibling-count($sibling-selector, $sibling-count, $fixed-widths:false) {
$fixed-len: length($fixed-widths);
$flexible-len: $sibling-count - $fixed-len;
$remaining-width: 100;
@if $fixed-widths != false {
@for $i from 1 through $fixed-len {
$w: nth($fixed-widths, $i);
$index-from-end: $sibling-count - $i + 1;
$remaining-width: $remaining-width - $w;
&:nth-child(#{$i}):nth-last-child(#{$index-from-end}){
width: $w * 1%;
}
}
$k: $flexible-len;
$child_num: $fixed-len;
@while $k > 0 {
//all remaining siblings should be same width
$child_num: $child_num + 1;
&:nth-child(#{$child_num}):nth-last-child(#{$k}) {
width: ($remaining-width/$flexible-len) * 1%;
}
$k: $k - 1;
}
}@else {
&:first-child:nth-last-child(#{$sibling-count}),
&:first-child:nth-last-child(#{$sibling-count}) ~ #{$sibling-selector} {
width: ($remaining-width/$sibling-count) * 1%;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment