Search code examples
javascriptcsshtmlanchorhighlight

CSS- Highlight a div when the id is linked to using an anchor?


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?


Solution

  • You can use the :target pseudo-class to select an element whose ID exactly matches the "fragment" part of the URL (the part after the # which jumps to a named anchor within the page).

    So for example, the following rule would apply to any element that you jump to with a URL fragment:

    :target {
       background-color: #ffa;
    }
    

    JS Fiddle demo.

    And the following rule would apply to a DIV called john, but only when the fragment in the current URL is #john (the fragment is the same as the ID of the DIV):

    div#john:target {
       background-color: #ffa;
    }
    

    If you click a link within the page which changes only fragment part of the URL, then the element selected by the :target pseudo-class will change.