How to add CSS style for focused anchor in HTML

There is a link on page 1 that takes you to a specific point on page 2

<a href="page2.html#position">MY TEXT HERE</a>

This will lead you directly to the anchor (position) on page 2 with the following code

<a name="position"> MORE TEXT HERE</a>

Now, my question is: how do I change the color of text and background when #position is in the URL?

For example: www.domainname.com/page2.html#position

This is the CSS that I used but does not work:

#position {
color:#ff0000;
background-color:#f5f36e;
}

Here is an example http://jsfiddle.net/jvtcj/2/

Thank you in advance!

+5
source share
5 answers

Use the selector :target:

a:target, /* or simply */
:target {
    /* CSS to style the focused/target element */
}

You would be better off using a idspecific element to get the focus, since the anchor names seem to have been dropped, if not completely out of date.

Literature:

+10

CSS3 :target peseudo: http://blog.teamtreehouse.com/stay-on-target

, <a name="destination">...</a>, , , id , , . <section id="destination">...</section>

+3
<a href="#position2" id="position">MY TEXT HERE</a>
...
<a name="position2" id="pos2"> MORE TEXT HERE</a>

... in css:

a[name=position2]:target{     
    background-color:green;
}
+1
source

Try using

<a name="position" class="position"> MORE TEXT HERE</a>

And in CSS use

.position {
color:#ff0000;
background-color:#f5f36e;
}

http://jsfiddle.net/jvtcj/4/

0
source

Add the id to the tag.

You can see how here using your example

http://jsfiddle.net/h5NZh/

<a id="position" href="#position">MY TEXT HERE</a>
0
source

All Articles