Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show / hide div on click with CSS

Tags:

css

I have a menu and three hidden divs that show up depending on what option the user selects. I would like to show / hide them on click using only CSS. I have it working with jquery right now but I want it to be accessible with js disabled. Somebody here provided this code for someone else but it only works with div:hover or div:active, when I change it to div:visited it doesn't work. Would I need to add something or perhaps this isn't the right way to do it? I appreciate any help :)

The thing is my client wants this particular divs to slide/fade when the menu is selected, but I still want them to display correctly with javascript turned off. Maybe z-index could do the trick...?

like image 408
brunn Avatar asked May 16 '11 15:05

brunn


2 Answers

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/

like image 144
Josh Avatar answered Sep 17 '22 14:09

Josh


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.

like image 33
James Fidlin Avatar answered Sep 20 '22 14:09

James Fidlin