Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I style even and odd elements?

Is it possible to use CSS pseudo-classes to select even and odd instances of list items?

I'd expect the following to produce a list of alternating colors, but instead I get a list of blue items:

<html>     <head>         <style>             li { color: blue }             li:odd { color:green }             li:even { color:red }         </style>     </head>     <body>         <ul>             <li>ho</li>             <li>ho</li>             <li>ho</li>             <li>ho</li>             <li>ho</li>         </ul>     </body> </html> 
like image 337
Armand Avatar asked Feb 22 '11 16:02

Armand


People also ask

How do you apply the same style to multiple elements?

When you group CSS selectors, you apply the same styles to several different elements without repeating the styles in your stylesheet. Instead of having two, three, or more CSS rules that do the same thing (set the color of something to red, for example), you use a single CSS rule that accomplishes the same thing.

What are 3 correct ways to target an element for styling?

URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element. The :target selector can be used to style the current active target element.

How do you select a child element in CSS?

The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.


1 Answers

Demo: http://jsfiddle.net/thirtydot/K3TuN/1323/

li {      color: black;  }  li:nth-child(odd) {      color: #777;  }  li:nth-child(even) {      color: blue;  }
<ul>      <li>ho</li>      <li>ho</li>      <li>ho</li>      <li>ho</li>      <li>ho</li>  </ul>

Documentation:

  • https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child
  • http://caniuse.com/css-sel3 (it works almost everywhere)
like image 161
thirtydot Avatar answered Oct 04 '22 15:10

thirtydot