Reputation: 2421
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
Upvotes: 15
Views: 43862
Reputation: 21
article>img:first-child {
border:1px solid #f00;
}
<article class="image">
<img src=... />
<img src= .../>
<div class="image">
<img src=... />
<img src= .../>
<img src= .../>
</div>
<img src= .../>
<img src= .../>
</div>
Upvotes: 2
Reputation: 7092
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.
Upvotes: 40
Reputation: 18024
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
Upvotes: 2
Reputation: 40970
You can do it using first-child
selector
.image img:first-child
{
height:500px;
width:200px;
border:15px solid Red;
}
Upvotes: 7
Reputation: 7519
The ':first-child' selector seems like it might be what you need.
http://www.w3schools.com/cssref/sel_firstchild.asp
Upvotes: 4