Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums CSS Using different background colors for each list item?

  • This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #40447
    AmruthPillai
    Member

    I’m trying to code a HTML markup that looks like the following image: [http://cl.ly/image/3u393l0H3a06](http://cl.ly/image/3u393l0H3a06 “”) but I haven’t quite been able to get it working properly.

    This is what I’ve come up with: [http://codepen.io/AmruthPillai/pen/twzFl](http://codepen.io/AmruthPillai/pen/twzFl “”). Each list item should have their own background-color.

    Any ideas how I can achieve this?

    #112591
    Kitty Giraudel
    Participant

    There are a bunch of ways to do this:
    – **Simple and cross-browser**: add a specific class to each list item, and give this class the wanted color (*.about { … }*)
    – **A little more complicated but cross-browser as well**: use an attribute selector on -let’s say- the alt the title (*a[title=about] { … }*)
    – **The CSS3 way**: use advanced CSS selectors to style each list item individually (*li:nth-child(2) a { … }*)

    #112594
    AmruthPillai
    Member

    @HugoGiraudel I wanted to try the CSS3 way, as you might have seen in my CodePen CSS, I’ve used _:first-child_ for the first _li_ element, but I’m not able to use _:nth-child(2,3,4,5,etc.)_ to select any of the other _li_ elements. Could you edit the CodePen by using the CSS3 way to select them and show me the correct usage?

    Thanks!

    #112596
    Kitty Giraudel
    Participant

    There you go: http://jsfiddle.net/pdY4A/1/

    By the way, the only element allowed inside a list (ul) is a list item (li). Then, you can add anchors (a) inside.

    #112597
    AmruthPillai
    Member

    Oh, okay! I finally understand how we should use the _:nth-child_ selector :)

    Thank you very much @HugoGiraudel!

    #112598
    Kitty Giraudel
    Participant

    You’re welcome.

Viewing 6 posts - 1 through 6 (of 6 total)
  • The forum ‘CSS’ is closed to new topics and replies.