Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

style 2nd element on the page with same class

Tags:

css

Hello is there a way with css to style the 2nd element on page with the same class slightly differently to the first.

For example I have two ul's on a page with a class of topbardropdownmenu. I want to give the 2nd ul a differen't background to the first. Is there a way to do this with out altering the html?

like image 389
Ben Paton Avatar asked Jan 06 '11 20:01

Ben Paton


2 Answers

What holds the <ul> elements? I'll assume a <div id = "lists">

/* First element */
div > ul.topbardropdownmenu:first-child{

}

/* Rest of the elements */
div > ul.topbardropdownmenu{

}

...alternatively

div > ul.topbardropdownmenu:not(:first-child)

like image 196
Stefan Kendall Avatar answered Nov 16 '22 00:11

Stefan Kendall


It depends which browsers your users are using, you might be able to use the nth-of-type css pseudo-selector:

ul.topbardropdownmenu:nth-of-type(2) {
   /* styles the second ul of class=topbardropdownmenu
}

If there's a particular pattern to the occurrence of these ul elements, you could use descendant and/or sibling selectors:

div > ul.topbardropdownmenu {
  /* styles all ul.topbardropdownmenu that are the immediate descendants of a div */
}

p + ul.topbardropdownmenu {
  /* styles all ul.topbardropdownmenu that immediately follow a p */
}
like image 26
David Thomas Avatar answered Nov 16 '22 01:11

David Thomas