Search code examples
htmlcsstabspseudo-class

Scroll snaps to position of anchor link - unwanted behaviour and inefficient implementation


I've created a simple tabbed content display using CSS and HTML. This code will be embedded around halfway down a much longer page with other content.

Here's the jsFiddle: http://jsfiddle.net/ollyf/R9rq2/

I've made use of :target but I'm not entirely sure how it works. Read a few tutorials but I don't fully understand the behaviour. I feel like this is bad/inefficient code.

  1. Is there a more efficient way to achieve this tabbed content effect?
  2. If not, how can I reveal the content without the scroll position snapping to the top of the DIV?

Solution

  • The :target pseudo selector is triggered by on page anchors. This means when your URL is http://www.example.com/#anchor1 #anchor1:target styles would be activated. The page is also scrolled to the #anchor1 element. This is the default functionality in browsers.

    The other option for achieving a tab effect is through the use of javascript. The concept is the same with javascript, you are still toggling the display attribute via click handlers. There are several ready made scripts available for tabs. Here is one example http://jquerytools.org/demos/tabs/index.html

    Hope this helps clear things up.