Sass - @while Directive



Description

Just as other control directives, the @while directive also takes SassScript expressions and until the statement evaluates to false, it iteratively outputs nested styles. The key thing to note is that counter variable needs to be incremented/decremented on each iteration.

Syntax

while(condition) {
   // CSS codes
}

Example

The following example demonstrates the the use of @while directive −

<html>
   <head>
      <title>Control Directives & Expressions</title>
      <link rel = "stylesheet" type = "text/css" href = "style.css"/>
   </head>

   <body>
      <p class = "paddding-50">This is line one with left padding 50. </p>
      <p class = "paddding-40">This is line two with left padding 40.</p>
      <p class = "paddding-30">This is line three with left padding 30. </p>
      <p class = "paddding-20">This is line four with left padding 20. </p>
      <p class = "paddding-10">This is line five with left padding 10. </p>
   </body>
</html>

Next, create file style.scss.

style.scss

$i: 50;
@while $i > 0 {
   .paddding-#{$i} { padding-left: 1px * $i; }
   $i: $i - 10;
}

You can tell SASS to watch the file and update the CSS whenever SASS file changes, by using the following command −

sass --watch C:\ruby\lib\sass\style.scss:style.css

Next, execute the above command; it will create the style.css file automatically with the following code −

style.css

.paddding-50 {
   padding-left: 50px;
}

.paddding-40 {
   padding-left: 40px; 
}

.paddding-30 {
   padding-left: 30px; 
}

.paddding-20 {
   padding-left: 20px; 
}

.paddding-10 {
   padding-left: 10px; 
}

Output

Let us carry out the following steps to see how the above given code works −

  • Save the above given html code in @while.html file.

  • Open this HTML file in a browser, an output is displayed as shown below.

Sass Control Directives & Expressions
sass_control_directives_expressions.htm
Advertisements