第一个图像的 CSS 选择器,仅当第一个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14260470/
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
CSS selector for first image, only if first child
提问by TobyG
Does anyone know if it's possible to define a CSS selector that selects the first image within a div, but only if it's the first child within the div.
有谁知道是否可以定义一个 CSS 选择器来选择 div 中的第一个图像,但前提是它是 div 中的第一个子元素。
In jQuery I would use a comparison something like this...
在 jQuery 中,我会使用这样的比较......
if ($('#div img:first-child') == $('#div>*:first-child')) {
...
}
回答by ScottS
By definition of "first-child", the selector (assuming your div
had an id
of div
)
根据 "first-child" 的定义,选择器(假设您div
有一个id
of div
)
#div img:first-child
already does that. First image of any div
is
已经这样做了。任何的第一张图片div
是
div img:first-child
However, as BoltClock's answer points out, the child selector is needed if you may have img
elements nested deeper in the div
.
但是,正如 BoltClock 的回答所指出的,如果您可能img
在div
.
回答by BoltClock
You don't need to do a comparison in jQuery if all you want to do is select that img
. Just combine your two selectors like so:
如果您只想选择 jQuery,则无需在 jQuery 中进行比较img
。只需像这样组合你的两个选择器:
#div > img:first-child
This works in both jQuery and CSS.
这适用于 jQuery 和 CSS。
回答by bookcasey
It's a simple CSS selector:
这是一个简单的 CSS 选择器:
#div:first-child img:first-child