Sass - @while Directive



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.


while(condition) {
   // CSS codes


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

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

      <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>

Next, create file 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 −


.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; 


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