How to target a specific <img> element of a div in CSS?

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.


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 }

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:

  • CSS3 selectors.

Tags:

Html

Css