Skip to content

Instantly share code, notes, and snippets.

@hadyfayed
Created January 28, 2014 01:17
Show Gist options
  • Save hadyfayed/8660744 to your computer and use it in GitHub Desktop.
Save hadyfayed/8660744 to your computer and use it in GitHub Desktop.
A Pen by Clint Brown.
<ul class="test test1">
<li>1</li>
<li>2</li>
</ul>
<ul class="test test1">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<div class="test test2">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>
<div class="test test3">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div class="test test3">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
<div class="test test3">
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
</div>

Set Child Width: Sass Mixin

Created a mixin for the :first-child/:nth-last-child(n) trick to set widths based on the number of child elements - includes support for custom rows (n elements/x per row).

A Pen by Clint Brown on CodePen.

License.

@import "compass";
@mixin set-child-width($container-width: 100%, $max-child-elements: 8, $hide-empty-container: true, $custom-rows: null) {
width: $container-width;
@if $hide-empty-container == true {
&:empty {
display: none;
}
}
@for $i from 1 through $max-child-elements {
> :first-child:nth-last-child(#{$i}),
> :first-child:nth-last-child(#{$i}) ~ * {
$width: #{$container-width / $i};
@if $custom-rows != null {
@each $row in $custom-rows {
$key: nth($row, 1);
$value: nth($row, 2);
@if $i >= $key {
$width: #{$container-width / $value};
}
}
}
width: $width;
}
}
}
// <li>
.test1 {
@include set-child-width(600px);
}
// <div>
.test2 {
@include set-child-width(600px);
}
// <div>
// Custom rows
// (min-child-elements elements-per-row)
// eg. if at least 4 elements, display 2 per row
// if at least 6 elements, display 3 per row
// if at least 8 elements, display 4 per row etc
.test3 {
@include set-child-width(600px, 8, true, (4 2, 6 3, 8 4));
}
body {
background: lightgray;
font-family: sans-serif;
}
.test {
position: relative;
clear: both;
float: left;
padding: 0;
margin: 0 0 20px 0;
}
.test > li,
.test > div {
float: left;
display: block;
padding: 8px 0;
margin: 0;
list-style: none;
background: grey;
color: white;
border-width: 1px 0 0 1px;
border-style: solid;
border-color: lightgrey;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
text-align: center;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment