TobyG
TobyG

Reputation: 1854

CSS selector for first image, only if first child

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.

In jQuery I would use a comparison something like this...

if ($('#div img:first-child') == $('#div>*:first-child')) {
  ...
}

Upvotes: 10

Views: 30179

Answers (3)

ScottS
ScottS

Reputation: 72261

By definition of "first-child", the selector (assuming your div had an id of div)

#div img:first-child

already does that. First image of any div is

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.

Upvotes: 15

BoltClock
BoltClock

Reputation: 723708

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:

#div > img:first-child

This works in both jQuery and CSS.

Upvotes: 14

bookcasey
bookcasey

Reputation: 40473

It's a simple CSS selector:

#div:first-child img:first-child

Upvotes: 3

Related Questions