Skip to content

Instantly share code, notes, and snippets.

@auxcoder
Last active February 28, 2017 14:51
Show Gist options
  • Save auxcoder/6952061b49c29e52fda05aeebe087636 to your computer and use it in GitHub Desktop.
Save auxcoder/6952061b49c29e52fda05aeebe087636 to your computer and use it in GitHub Desktop.
Examples of control flow and loop iteration in SASS

Sass control flow and loop iterations

@if @else

The @if control directive takes an expression and processes its block of styles if the expression is true. This example let us define styles base in the devise orientation.

@mixin iPad($orientation: null){
	@media only screen
	and (min-device-width : 768px)
	and (max-device-width : 1024px){
		@if ($orientation == landscape){
			@media (orientation : landscape){
				@content;
			}
		} @else if ($orientation == portrait){
			@media (orientation : portrait){
				@content;
			}
		} @else {
			@content;
		}
	}
}

// use
.container{
	padding: 20px auto;
	@include iPad(portrait){
		padding: 5px auto;
	}
}

output

@media only screen and (max-device-width: 1024px) and (min-device-width: 768px) and (orientation: portrait)
.container {
	padding: 5px auto;
}

@for

The first option is @for $var from <start> through <end> which starts at <start> and loops "through" each iteration and ends at <end>. Pretty straight forward.

@for $i from 1 through 4 {
	.col-#{$i}{
		width: 100% / $i
	}
}

@each

For each item in collection iterate

$pets: cat dog rabit
@each $animal in $$pets{
	.photo-#{$animal}{
		background: image-url("images/#{$animal}.png") no-repeat
	}
}

output

.photo-cat{
	background: image-url("images/cat.png") no-repeat;
}
.photo-dog{
	background: image-url("images/dog.png") no-repeat;
}
.photo-rabit{
	background: image-url("images/rabit.png") no-repeat;
}

@while

While the expresion evaluates to true it iterates over the nested

$cols: 3;
@while $cols > 0{
	.col-#{$cols}{
		width: 100% / $cols;
	}
	$cols: $cols - 1;
}

output

.col-1{
	width: 33.333%;
}
.col-2{
	width: 33.333%;
}
.col-3{
	width: 33.333%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment