3

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;

  }
}

1 Answer 1

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.