Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have this html :

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

And I would to apply css only to the first image of div of class image without having to add a class to my first img (in that case, I would do .image .img1 but is there another way ?

Thanks a lot for your help

like image 985
Reveclair Avatar asked Mar 22 '13 14:03

Reveclair


People also ask

How do I target an image in a div?

You can target the img tag and not even worry about the div tag. These attribute selectors select by the "begins with". These select by "contains". Or you can select by the exact src.

How do I select the first image in CSS?

You need to use .is() instead.

How would you select all the IMG tags on a page?

The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").

How do I select an image tag in CSS?

The selector img . myClass will select an element with a class of myClass that is a descendant of an img element.


2 Answers

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.

like image 74
Michael Avatar answered Sep 21 '22 15:09

Michael


You can do it using first-child selector

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

JS Fiddle Example

like image 41
Sachin Avatar answered Sep 19 '22 15:09

Sachin