Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I make different backgrounds for multiple selectors in CSS?

I have a div with five sections in it. I’d like to have different background colors for each one.

Usually, one would create a class for each:

CSS

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.b1 {background-color: blue;}
.b2 {background-color: red;}
.b3 {background-color: black;}
.b4 {background-color: beige;}
.b5 {background-color: blue;}

HTML

<div>
   <section class="b1">Block 1</section>
   <section class="b2">Block 2</section>
   <section class="b3">Block 3</section>
   <section class="b4">Block 4</section>
   <section class="b5">Block 5</section>
</div>

But I recently saw someone else’s HTML that had different colors for each one, yet there were no classes in any of the section tags. Is there some other way of doing this in CSS?

Tried to create different background colors for each section without classes in each HTML tag.

>Solution :

Using javascript, you access to the child elements and add the color, there is an example:

let container = document.getElementById('itemsContainer');
let childItems = Array.from(container.children);
childItems.forEach(function (element, index) {
    if (index == 0) {
        element.style.backgroundColor = 'blue';
    }
    if (index == 1) {
        element.style.backgroundColor = 'red';
    }
    /*
    if .... n times
    */
});

To makeit more clean, you can save the colors value in an array and do this:

let container = document.getElementById('itemsContainer');
let childItems = Array.from(container.children);
let colorsValue = ['blue', 'red', 'black', 'beige', 'blue'];
childItems.forEach(function (element, index) {
    element.style.backgroundColor = colorsValue[index];
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading