skip to Main Content

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

.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.

2

Answers


  1. 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];
    });
    
    Login or Signup to reply.
  2. I don’t see why you want to avoid classes. That being said, if your sections have same parent you can use :nth-of-type pseudo class:

    section:nth-of-type(1) {
      background-color: blue;
    }
    
    section:nth-of-type(2) {
      background-color: red;
    }
    
    section:nth-of-type(3) {
      background-color: black;
    }
    
    section:nth-of-type(4) {
      background-color: beige;
    }
    
    section:nth-of-type(5) {
      background-color: blue;
    }
    <div>
      <section>Block 1</section>
      <section>Block 2</section>
      <section>Block 3</section>
      <section>Block 4</section>
      <section>Block 5</section>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search