How to add CSS style to focused anchor in HTML
Solution 1
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:
Solution 2
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>
Solution 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;
}
![Giovanni](https://i.stack.imgur.com/4dzc9.jpg?s=256&g=1)
Giovanni
Updated on March 07, 2020Comments
-
Giovanni over 4 years
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!
-
Giovanni over 11 yearsThank you for your help this worked. I also had to add the class
-
Giovanni over 11 yearsThanks for your help, I added the class and it worked, I also had to give the CSS a :target