Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomize float and percentage in SASS?

Tags:

css

sass

How to randomize float (for opacity) and percentage (for position) in SASS? https://codepen.io/anon/pen/XZMXMM

<div class="parent">
  <div class="child"></div>
  <div class="child"></div>
</div>

For position I am only able to randomize by px, if I put % it doesn't work.

.child {
  position: absolute;
  top: 50px;
  background: #333;
  width: 15px;
  height: 15px;
}

@for $i from 0 to 15 {
  .parent .child:nth-child(#{$i}) {

     // Instead of px this should randomize by percent up to 100% (20%, 45%, 77%...)
     left: random(100) + px; 

     // This should randomize opacity (0.5, 0.7, 0.9, ...)
     opacity: 1;

  }
}
like image 450
Ivan Topić Avatar asked Oct 29 '25 13:10

Ivan Topić


1 Answers

You can use the following solution using the percentage function:

@for $i from 0 to 15 {
  .parent .child:nth-child(#{$i}) {

    //this should randomize by percent up to 100% (20%, 45%, 77%, ...)
    left: percentage(random(100) / 100);

    //this should randomize opacity (0.5, 0.7, 0.9, ...)
    opacity: random(10) / 10;
  }
}

You can also use the original answer without the percentage function:

@for $i from 0 to 15 {
  .parent .child:nth-child(#{$i}) {

    //this should randomize by percent up to 100% (20%, 45%, 77%, ...)
    left: random(100) / 100 * 100%;

    //this should randomize opacity (0.5, 0.7, 0.9, ...)
    opacity: random(10) / 10;
  }
}

You can find a working demo on CodePen.

like image 161
Sebastian Brosch Avatar answered Oct 31 '25 03:10

Sebastian Brosch