Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show/hide div on click with stricly HTML/CSS

Tags:

html

css

hide

show

I'm working on a sidebar for my personal website and I'm looking to show/hide a Facebook follow button when visitors click on a Facebook icon. I am wondering if it is possible with stricly HTML/CSS and if not, what would be the easiest way to do it with JavaScript. I've seen many jQuery solutions around but I have yet to find a purely HTML/CSS one.

<div class="sidebar-follow">                            
    <div class="sidebar-follow-icon">
        <img src="/follow_facebook.jpg" alt="Follow on Facebook" height="32" width="160">
    </div>
    <div class="sidebar-follow-button">
        This is the follow button.
    </div>                      
</div>

Clicking on .sidebar-follow-icon should reveal .sidebar-follow-button and clicking again on .sidebar-follow-icon show hide .sidebar-follow-button.

like image 530
LaGuille Avatar asked Aug 30 '25 16:08

LaGuille


2 Answers

Html

<label for="toggle-1"> Button </label>
<input type="checkbox" id="toggle-1">
<div class="facebook"> Facebook Content</div>

CSS

/* Checkbox Hack */

input[type=checkbox] {
   position: absolute;
   top: -9999px;
   left: -9999px;
}
label { 
  -webkit-appearance: push-button;
  -moz-appearance: button; 
  display: inline-block;
  margin: 60px 0 10px 0;
  cursor: pointer;
}

/* Default State */
.facebook {
   background: green;
   width: 400px;
   height: 100px;
   line-height: 100px;
   color: white;
   text-align: center;
}

/* Toggled State */
input[type=checkbox]:checked ~ .facebook {
   display: none;
}

fiddle Here And more About this csstricks

like image 155
Ghostff Avatar answered Sep 02 '25 05:09

Ghostff


This is honestly not typically done in HTML / CSS. It's best suited for Javascript, JQuery, and the like.

But it got me thinking... is it possible.

And here's what I came up with that I think is the closest that you can get using pure CSS: http://jsfiddle.net/a92pkeqw/

My reasoning: the only element that can save it's 'state' is the checkbox. This is, therefore, the only element that can produce a toggling effect. Using the toggle and the ~ selector in CSS, it was possible to edit the styling of another element, in this case change the visibility property.

HTML:

<input type="checkbox" class="toggle"></input>

<div class="toggled">
    Text that be hidden dynamically!
</div>

CSS:

input[type='checkbox']:checked ~ .toggled
{
    visibility: hidden;
}

input[type='checkbox'] ~ .toggled
{
    visibility: visible;
}
like image 28
James Taylor Avatar answered Sep 02 '25 04:09

James Taylor