Show / hide div on click with CSS

This can be achieved by attaching a "tabindex" to an element. This will make that element "clickable". You can then use :focus to select your hidden div as follows...

.clicker {
width:100px;
height:100px;
background-color:blue;
outline:none;
cursor:pointer;
}

.hiddendiv{
display:none;
height:200px;
background-color:green;
}

.clicker:focus + .hiddendiv{
display:block;
}
<html>
<head>
</head>
<body>

<div>
<div class="clicker" tabindex="1">Click me</div>
<div class="hiddendiv"></div>
</div>

</body>

</html>

The + selector will select the nearest element AFTER the "clicker" div. You can use other selectors but I believe there is no current way to select an element that is not a sibling or child.


For a CSS-only solution, try using the checkbox hack. Basically, the idea is to use a checkbox and assign different styles based on whether the box is checked or not used the :checked pseudo selector. The checkbox can be hidden, if need be, by attaching it to a label.

link to dabblet (not mine): http://dabblet.com/gist/1506530

link to CSS Tricks article: http://css-tricks.com/the-checkbox-hack/

Tags:

Css