What is the simplest way to implement pure css show/hide?

Kzqai picture Kzqai · May 31, 2011 · Viewed 9.2k times · Source

I discovered the <details> element for html5, and that made me want to determine whether it was possible to implement a simple and reusable show/hide via css alone.

I have created a show/hide mechanism in the past for showing and hiding content by giving two elements relative positioning and one a negative z-index, and then decreasing the z-index of the front element on hover (and increasing the z-index of the back element on hover).

However, that method only works for elements that are in the same location. Are there other techniques for simulating show/hide on non-overlapping elements? e.g. a title that causes a section of descriptive text to display.

Trivial example code that I would like to be able to apply a show/hide to:

<div id='container'>
<h3 id='show-hide-trigger'>summary</h3>
<p id='show-hide-text'>Paragraph of detail text paragraph Paragraph of detail text paragraph Paragraph of detail text paragraph Paragraph of detail text paragraph</p>
</div>

And yes, I do know that jQuery exists.

Answer

Gabriele Petrioli picture Gabriele Petrioli · May 31, 2011

there is a plethora of options based on the structure (for modern browsers).

Have a look at the

  1. selector + selector  adjacent sibling selector
  2. selector ~ selector  general sibling selector
  3. selector selector      descendant selector
  4. selector > selector  child selector

These can be combined with classes / ids / pseudo-selectors like :hover etc, and create a big list of options.

here is a small demo i made to showcase them : http://jsfiddle.net/gaby/8v9Yz/