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
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.
You need to use .is() instead.
The * selector selects all elements. The * selector can also select all elements inside another element (See "More Examples").
The selector img . myClass will select an element with a class of myClass that is a descendant of an img element.
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.
You can do it using first-child
selector
.image img:first-child
{
height:500px;
width:200px;
border:15px solid Red;
}
JS Fiddle Example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With