开发者

style 2nd element on the page with same class

开发者 https://www.devze.com 2023-02-02 17:27 出处:网络
Hello is there a way with css to style the 2nd element on page with the same class slightly differently to the first.

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 开发者_Go百科to give the 2nd ul a differen't background to the first. Is there a way to do this with out altering the html?


You can do it with the :nth-child() pseudo-selector. It is CSS3 though, and not supported in some browsers (e.g. <=IE8 & <=FF3.0 doesnt support it).

.topbardropdownmenu:nth-child(2) { background: #FF0000; }

You could do it with JavaScript in a cross-browser compatible way though, if that's an option for you.


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)


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 */
}


Look at the CSS3 nth-child() pseudo-class.


You can use :nth-child http://css-tricks.com/how-nth-child-works/ but IE may struggle with it. Consider this jQuery alternative:

$(".class").eq(1).css();

http://api.jquery.com/eq/

0

精彩评论

暂无评论...
验证码 换一张
取 消