11

I've a code of some what like this:

<div id="foo"> <img src="bar.png" align="right"> <img src="cat.png" align="right"> </div> 

Now my question is how do I target a specific image in CSS when having the above code?

3
  • Target how? CSS selectors let you target 'nth-child' type stuff, by tag attributes, etc... Commented Apr 5, 2012 at 21:27
  • 1
    Are you implying that you cannot change the HTML? Also note that align on <img> was deprecated in HTML4 and is now obsolete in HTML5. Commented Apr 5, 2012 at 21:27
  • Yup, I'm forced to use the above code. Commented Apr 5, 2012 at 21:39

6 Answers 6

17

It depends entirely upon which image you want to target. Assuming it's the first (though the implementations are similar for both) image:

#foo img[src="bar.png"] { /* css */ } #foo img[src^="bar.png"] { /* css */ } #foo img:first-child { /* css */ } #foo img:nth-of-type(1) { /* css */ } 

References:

Sign up to request clarification or add additional context in comments.

Comments

17

I don't know why everyone is so fixed on the #foo div. You can target the img tag and not even worry about the div tag. These attribute selectors select by the "begins with".

img[src^=bar] { css } img[src^=cat] { css } 

These select by "contains".

img[src*="bar"] { css } img[src*="cat"] { css } 

Or you can select by the exact src.

img[src="bar.png"] { css } img[src="cat.png"] { css } 

If you want to target them both, then you could use the div id.

#foo img { css } 

For just one of the images, there is no need to worry about the #foo div at all.

2 Comments

because OP says "in the div"
I get that. I wasn't concerned with the div. It's irrelevant. OP wants to target the img not the div.
14

You can add a class to the images OR

.foo img:nth-child(2) { css here } 

or

.foo img:first-child { css here } .foo img:last-child { css here } 

Comments

1
div > img:first-child {/*the first image*/} div > img:last-child {/*the last image*/} 

That should do it.

Comments

0

All of the following solutions only work in recent browsers.

You can select by child position:

 #foo img:first-child { /* for the bar */ } #foo img:nth-child(2) { /* for the cat */ } 

You can select by child position, counting only images:

 #foo img:first-of-type { /* for the bar */ } #foo img:nth-of-type(2) { /* for the cat */ } 

You can select by image URL:

 #foo img[src^=bar] { /* for the bar */ } #foo img[src^=cat] { /* for the cat */ } 

Comments

0
#foo > IMG:first-child {/* first of two IMGs */} #foo > IMG + IMG {/* second one */} 

Works in all browsers including IE7+.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.