什么 CSS 选择器可用于选择另一个 div 中的第一个 div
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3747547/
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
What CSS selector can be used to select the first div within another div
提问by GregH
I have something like:
我有类似的东西:
<div id="content>
<h1>Welcome to Motor City Deli!</h1>
<div style=" font-size: 1.2em; font-weight: bolder;">Sep 19, 2010</div>
<div > ... </div>
What is the css selector for the second div (1st div within the "content" div) such that I can set the font color of the date within that div?
第二个 div(“内容”div 中的第一个 div)的 css 选择器是什么,以便我可以在该 div 中设置日期的字体颜色?
回答by Jeremy Moritz
The MOST CORRECT answer to your question is...
你的问题最正确的答案是......
#content > div:first-of-type { /* css */ }
This will apply the CSS to the first div that is a direct child of #content (which may or may not be the first child element of #content)
这会将 CSS 应用于第一个 div,它是 #content 的直接子元素(可能是也可能不是 #content 的第一个子元素)
Another option:
另外一个选项:
#content > div:nth-of-type(1) { /* css */ }
回答by Capt Otis
You want
你要
#content div:first-child {
/*css*/
}
回答by Stan Rogers
If we can assume that the H1 is always going to be there, then
如果我们可以假设 H1 总是会在那里,那么
div h1+div {...}
but don't be afraid to specify the id of the content div:
但不要害怕指定内容 div 的 id:
#content h1+div {...}
That's about as good as you can get cross-browser right now without resorting to a JavaScript library like jQuery. Using h1+div ensures that only the first div after the H1 gets the style. There are alternatives, but they rely on CSS3 selectors, and thus won't work on most IE installs.
这与您现在无需求助于像 jQuery 这样的 JavaScript 库就可以跨浏览器一样好。使用 h1+div 确保只有 H1 之后的第一个 div 获得样式。有替代方案,但它们依赖于 CSS3 选择器,因此不适用于大多数 IE 安装。
回答by Josh Leitzel
The closest thing to what you're looking for is the :first-child pseudoclass; unfortunately this will not work in your case because you have an <h1>
before the <div>s
. What I would suggest is that you either add a class to the <div>
, like <div class="first">
and then style it that way, or use jQuery if you really can't add a class:
与您正在寻找的最接近的是:first-child 伪类;不幸的是,这在您的情况下不起作用,因为您<h1>
在<div>s
. 我的建议是,您可以向<div>
, like添加一个类<div class="first">
,然后以这种方式设置样式,或者如果您确实无法添加类,则使用 jQuery:
$('#content > div:first')
$('#content > div:first')