How to set the background color of sections of a page with CSS?

0

Within the body of my HTML document I have a sequence of 5 sections, this number may vary depending on the situation.

I would like to set a different background for each section "" , ie jump 1 section and apply a background-color, skip another and apply again the same style, successive times until the last section of the page.

    
asked by anonymous 27.11.2017 / 02:15

2 answers

2

There are specific selectors to pick up even and odd elements, which allow you to do what you want with ease.

You can start by formatting all the elements normally and overrides the formatting for the pairs with the selector:

section:nth-child(even)

Or for odd ones with:

section:nth-child(odd)

Example:

section {
  background-color:lightBlue;
  height:80px;
}

section:nth-child(even){ /*pares com fundo azul*/
  background-color:blue;
}
<section></section>
<section></section>
<section></section>
<section></section>
<section></section>

Documentation for nth-child in MDN

    
27.11.2017 / 02:21
2

Using :nth-child(even) or :nth-of-type(even) , you can easily get the desired result. It will select all that were "even", ie all pairs.

Look at this example at link :

/* Propósito Estético */
section {
  color: white;
  padding: 2em 1.5em;
}

/* Pares */
section:nth-child(even) {
  background-color: #333;
  color: #ccc;
}

/* Impares */
section:nth-child(odd) {
  background-color: #ccc;
  color: #333
}
<section>Section #1</section>
<section>Section #2</section>
<section>Section #3</section>
<section>Section #4</section>
<section>Section #5</section>

Remembering that there are a thousand and one ways to use these pseudo-classes. This site lists almost all the ways you can use: link

    
27.11.2017 / 02:29