Generating Random Color with SASS

With the random() function in Sass, we can do this as follows;

.box {
    background-color: rgb(random(255), random(255), random(255));
}

If you want to create a low opacity value, you can use rgba ().

.box {
    background-color: rgba(random(255), random(255), random(255), .3);
}

For example, if we had an html structure like this;

<ul>
    <li>1. box</li>
    <li>2. box</li>
    <li>3. box</li>
    <li>4. box</li>
</ul>

If the css was like this;

ul {
    display: flex;
    width: 600px;
    margin: 0 -10px;
    li {
        flex: 1;
        margin: 0 10px;
        height: 150px;
        display: flex;
        align-items: center;
        justify-content: center;
    }
}

We could set up a for loop with sass and background each of them as follows;

@for $i from 1 through 4 {
    ul li:nth-child(#{$i}) {
        background-color: rgba(random(255), random(255), random(255), .3);
    }
}

See you in our next article :)

Comments

There are no comments, make the firs comment