How to select first img tag in a div with many img tag?

If you want the first image inside a DIV (and there might be other elements preceding it) you need first-of-type rather than first-child

div > img:first-of-type {}

consider the following html

<div>
    <p>paragraph, this is :first-child</p>
    <img src="..."><!-- this is img:first-of-type -->
</div>

More details can be found at https://developer.mozilla.org/en-US/docs/CSS/:first-of-type


You can use the :first-child selector to do this.

You could also use :nth-child(1) (where the 1 is = to the first child, 2 is equal to the second child etc.)

Finally, a more proper way would be the use of :first-of-type

For example:

div.image img:first-child {}

Or:

div.image img:nth-child(1) {}

Or (if there are other elements, say an <h1> that comes prior to any images:

div img:first-of-type

If you have the potential for having a div with class image which has images inside it and also another div which has images in it, like this:

HTML:

<div class="image">
   <img src=... />
   <img src= .../>
   <div class="image">
      <img src=... />
      <img src= .../>
   </div>
</div>

Then use these selectors:

For example:

div.image > img:first-child {}

Or:

div.image > img:nth-child(1) {}

Or:

div > img:first-of-type

Documentation on :first-child and on :nth-child() and on :first-of-type and on child combinator.

Note that :nth-child() and :first-of-type are CSS3 selectors, which carry some limited support when using IE. See Can I use CSS3 Selectors for browser support details.

Consider something like Selectivizr to help standardize IE.


The ':first-child' selector seems like it might be what you need.

http://www.w3schools.com/cssref/sel_firstchild.asp


You can do it using first-child selector

.image img:first-child
{
  height:500px;
  width:200px;
  border:15px solid Red;    
}

JS Fiddle Example