Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

CSS CSS Selectors Advanced Selectors :root and :target

Andrew Husted
Andrew Husted
11,271 Points

I want to change src property of image using :target.

I set img id to color. Link targets #color.

CSS rule is #color:target {src="dif-img.jpg";}

Can someone help?

2 Answers

Steven Parker
Steven Parker
231,271 Points

In a CSS rule, prpperty names and values should be separated by a colon. But also, "src" is not a CSS property. The closest equivalent CSS property would be "content":

#color:target {
  content: url("dif-img.jpg");
}

Ssome browsers might only support the "content" property for pseudo-elements. If so, you could set the background-image of another kind of element (such as a "div") and have the CSS change that instead.

Cool! Didn't know you could do that.

You can't change the value of an HTML attribute with CSS. CSS is meant to modify an element's presentation, not content. You can, however, change an element's background-image property with CSS. Changing an element's src attribute can be done with JavaScript:

let image = document.getElementById('color');
image.src = 'dif-img.jpg';

Here's a great writeup on how to use the :target pseudo-class on CSS-Tricks: https://css-tricks.com/on-target/.