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

Asked

Viewed 37 times

0

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

I would like to define a different highlight (background) for each Service "par", i.e., skip 1 Section and apply a background-color, skip another and apply again the same style, successively until the last page Section.

2 answers

2

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

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

section:nth-child(even)

Or for odd notes 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 the nth-child on MDN

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.

Note this example in http://cssdeck.com/labs/rib8dumb:

/* 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 every way you can use: http://nthmaster.com

Browser other questions tagged

You are not signed in. Login or sign up in order to post.