Is there any way to randomize padding in CSS/JavaScript?

Viewed 88

So I've been trying to make a web-app and thought it would be cool to have "cards" with randomized top padding.

Here's a screen-shot of what I'm trying to achieve:

https://imgur.com/FyKHfRV

And here's what I have:

https://imgur.com/JkaUGQp

This is the JavaScript I tried to use, but it failed.

document.getElementById("card").addEventListener("load", randomCards);
let root = document.card;

function randomCards() {
    root.style.setProperty('cardpadding-top', Math.floor(Math.random() * 6) + "px");
});

And here's the HTML:

<body>
    <div class="scroll-wrap">
        <div id="card"></div>
        <div id="card"></div>
        <div id="card"></div>
        <div id="card"></div>
        <div id="card"></div>
    </div>
</body>

Any help is appreciated :)

2 Answers

Here is how to do it. I have used class="card" instead of id and also used querySelectorAll() to get all the cards and loop over each and set the styles randomly using Math.random().

document.querySelectorAll(".card").forEach(card=>{
  card.style.paddingTop = Math.floor(Math.random() * 20) + "px"
})

WORKING CODE DEMO:

document.querySelectorAll(".card").forEach(card=>{
  card.style.paddingTop = Math.floor(Math.random() * 20) + "px"
})
.scroll-wrap{ height:400px; display:flex; align-items:center}
.card{
  height:100px;
  width:100px;
  background:blue;
  display:inline-block;
  margin:0 5px;
}
<div class="scroll-wrap">
        <div class="card"></div>
        <div class="card"></div>
        <div class="card"></div>
        <div class="card"></div>
        <div class="card"></div>
    </div>

Based on your example, you should try this, swap id with class attribute go through each of your div's and assign random paddings.

JS

 document.addEventListener("load", randomCards);
 function randomCards() {
   document.querySelectorAll('.card').forEach(card => {
     card.style.paddingTop = Math.floor(Math.random() * 6) + "px";
   });
 }

HTML

 <div class="scroll-wrap">
        <div class="card"></div>
        <div class="card"></div>
        <div class="card"></div>
        <div class="card"></div>
        <div class="card"></div>
    </div>
Related