Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add CSS style to focused anchor in HTML

Tags:

html

css

anchor

On page 1 there is a link which takes you to a certain point on page 2

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

This takes you straight to the anchor (position) on page 2 with the following code

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

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

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

This is the CSS I used but doesn't work:

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

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

Thank you in advance!

like image 541
Giovanni Avatar asked Mar 06 '13 22:03

Giovanni


2 Answers

Use the :target selector:

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

You'd be better off using the id of a particular element to receive the focus, since named-anchors seem to have been dropped, if not deprecated entirely.

References:

  • CSS selectors, level 3.
like image 165
David Thomas Avatar answered Oct 12 '22 03:10

David Thomas


You can use the CSS3 :target peseudo selector: http://blog.teamtreehouse.com/stay-on-target

Also, don't use the old myth <a name="destination">...</a>, all you need is to id the section you want to jump to, e.g. <section id="destination">...</section>

like image 27
powerbuoy Avatar answered Oct 12 '22 03:10

powerbuoy