Fiddle to your heart's content
HTML
<div>
<a tabindex="1" class="testA">Test A</a> | <a tabindex="2" class="testB">Test B</a>
<div class="hiddendiv" id="testA">1</div>
<div class="hiddendiv" id="testB">2</div>
</div>
CSS
.hiddendiv {display: none; }
.testA:focus ~ #testA {display: block; }
.testB:focus ~ #testB {display: block; }
Benefits
You can put your menu links horizontally = one after the other in HTML code, and then you can put all the content one after another in the HTML code, after the menu.
In other words - other solutions offer an accordion approach where you click a link and the content appears immediately after the link. The next link then appears after that content.
With this approach you don't get the accordion effect. Rather, all links remain in a fixed position and clicking any link simply updates the displayed content. There is also no limitation on content height.
How it works
In your HTML, you first have a DIV
. Everything else sits inside this DIV
. This is important - it means every element in your solution (in this case, A
for links, and DIV
for content), is a sibling to every other element.
Secondly, the anchor tags (A
) have a tabindex
property. This makes them clickable and therefore they can get focus. We need that for the CSS to work. These could equally be DIV
s but I like using A
for links - and they'll be styled like my other anchors.
Third, each menu item has a unique class name. This is so that in the CSS we can identify each menu item individually.
Fourth, every content item is a DIV
, and has the class="hiddendiv"
. However each each content item has a unique id
.
In your CSS, we set all .hiddendiv
elements to display:none;
- that is, we hide them all.
Secondly, for each menu item we have a line of CSS. This means if you add more menu items (ie. and more hidden content), you will have to update your CSS, yes.
Third, the CSS is saying that when .testA
gets focus (.testA:focus
) then the corresponding DIV
, identified by ID (#testA
) should be displayed.
Last, when I just said "the corresponding DIV
", the trick here is the tilde character (~
) - this selector will select a sibling element, and it does not have to be the very next element, that matches the selector which, in this case, is the unique ID value (#testA
).
It is this tilde that makes this solution different than others offered and this lets you simply update some "display panel" with different content, based on clicking one of those links, and you are not as constrained when it comes to where/how you organise your HTML. All you need, though, is to ensure your hidden DIV
s are contained within the same parent element as your clickable links.
Season to taste.