80

What I am attempting to do is to highlight a div with a certain id, when It has been referred to by an anchor on another page IE:

User clicks link href="qw.html#test", when the page is loaded, then the div with the id="test" is highlighted so that the user can see it clearly.

I'm sure that I've seen a CSS3 example where a div is highlighted if it was linked to. Or was it JavaScript?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
harley_woop
  • 1,739
  • 4
  • 15
  • 28

3 Answers3

154

You need to use the :target pseudo-class:

:target {
   background-color: #ffa;
}

JS Fiddle demo.

Carson
  • 6,105
  • 2
  • 37
  • 45
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • 2
    @DavidThomas, can this be done for *any* target? Or do I have to specify the id each time? – DAE Mar 12 '18 at 12:41
  • 1
    @DAE: the 'target' is identified by the URL fragment identifier (the `#elementID`), so it can only work for an element that has an `id` and has its `id` in the URL like so: `http://example.com#elementID` – David Thomas Mar 12 '18 at 13:56
  • 1
    @DavidThomas actually in the end i tried a:target and it works fine for my purposes :) – DAE Mar 13 '18 at 12:43
  • If answer was self contained, then it would be worth an up vote. As is it misses the important part: how to create a target is only on the other site. – ctrl-alt-delor May 30 '22 at 07:05
0

JavaScript can be used to dynamically add/change the class of the div:

If you have:

<div id="test"></div>

Javascript function, executed by the click of the anchor:

document.getElementById("test").className += " highlighted";

Result:

<div id="test" class=" highlighted"></div>
HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
blearn
  • 1,198
  • 10
  • 17
0

You can do this in JavaScript. Refer to How to get the anchor from the URL using jQuery? on how to get the anchor from URL and then it can be something simple like

document.getElementById(hash).style.backgroundColor="Yellow";
Community
  • 1
  • 1
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
  • 1
    That is helpful thanks but I like to just use CSS if possible. Thanks for the alternative anyways. – harley_woop Jun 21 '12 at 16:09
  • And I could not get this to work when linking within the file (i.e. refreshing the page but with a different anchor) while the CSS style approach does work for m. – zsalya Jul 21 '23 at 11:34