CSS 页面上具有相同类的第二个元素的样式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4619756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:25:21  来源:igfitidea点击:

style 2nd element on the page with same class

css

提问by Ben Paton

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

您好,有没有一种方法可以使用 css 为页面上的第二个元素设置与第一个略有不同的相同类的样式。

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?

例如,我在一个带有 topbardropdownmenu 类的页面上有两个 ul。我想给第二个 ul 一个与第一个不同的背景。有没有办法在不改变 html 的情况下做到这一点?

回答by simshaun

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).

您可以使用:nth-child()伪选择器来完成。但是它是 CSS3,并且在某些浏览器中不受支持(例如 <=IE8 & <=FF3.0 不支持它)。

.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.

不过,如果这是您的选择,您可以以跨浏览器兼容的方式使用 JavaScript 来完成。

回答by Stefan Kendall

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

什么保持<ul>元素?我会假设一个<div id = "lists">

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

}

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

}

...alternatively

...或者

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

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

回答by David says reinstate Monica

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

这取决于您的用户使用的浏览器,您可以使用nth-of-typecss 伪选择器:

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

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

如果这些ul元素的出现有特定的模式,您可以使用后代和/或兄弟选择器:

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

回答by ChrisJ

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

查看 CSS3 nth-child() 伪类

回答by Matt Asbury

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

您可以使用 :nth-child http://css-tricks.com/how-nth-child-works/但 IE 可能会遇到困难。考虑这个 jQuery 替代方案:

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

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

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