Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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')) {
  ...
}
like image 569
TobyG Avatar asked Jan 10 '13 14:01

TobyG


2 Answers

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.

like image 193
ScottS Avatar answered Oct 18 '22 07:10

ScottS


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.

like image 29
BoltClock Avatar answered Oct 18 '22 07:10

BoltClock