CSS - styling on the web

Hello!

I’m a beginner.
Studying CSS, an interesting question arose.

  • How can the headings of the same value be changed to a different color?
    From the example available to us:

    h2 {
    color: red;
    }

I want every subsequent H2 heading to have a different color.

  • What do you need to do in CSS for this?
    The old version of HTML is clear.
    I want to check my guesses.

Thank you.

Hi there @pseudonym, and welcome to the community.

So you are looking at the above CSS rule, which makes all <h2>s red, but you are asking how we can create a rule that makes the first <h2> red, the next one yellow, the next one blue, etc.

This isn’t too hard to do, but there isn’t a very compact way to do it.

You could specify classes for the different colors you want:

.primary-highlight {
  color: red;
}

.secondary-highlight {
  color: yellow;
}

.alt-highlight {
  color: blue;
}

and then add those classes to the HTML:

<h2 class="primary-highlight">First</h2>
<h2 class="secondary-highlight">Second</h2>
<h2 class="alt-highlight">Third</h2>

Or you could use advanced pseudo-classes to select every third <h2> and turn it red, then every third one plus one and turn it yellow, etc.:

h2:nth-of-type(3n) {
  color: red;
}

h2:nth-of-type(3n + 1) {
  color: yellow;
}

h2:nth-of-type(3n + 2) {
  color: blue;
}

This is better as you don’t need to keep specifying class names in your HTML, and it will work no matter how many <h2>s you have in your document. But it is harder to control — what if you want to add in two yellow <h2>s together, just in one place?

You could also vary the <h2> colors using JavaScript, maybe something like this:

const headings = document.querySelectorAll('h2');

for(let i = 0; i < headings.length; i++) {
  if((i + 3) % 3 === 0) {
    headings[i].style.color = 'red';
  } else if((i + 2) % 3 === 0) {
    headings[i].style.color = 'yellow';
  } else if((i + 1) % 3 === 0) {
    headings[i].style.color = 'blue';
  }
}

But with JS you could do anything like — set every <h2> to a random color, for example.

I hope that helps :wink:

Hello chrisdavidmills!
Thank you for your prompt and helpful reply.
It’s great!

Yours faithfully,
Sergei.

вт, 5 янв. 2021 г. в 13:21, chrisdavidmills via Mozilla Discourse <notifications@discourse.mozilla.org>:

@pseudonym you are very welcome.