Thursday 24 November 2016

CSS only slide in navs

I could have kicked myself for not figuring this out earlier. Pure CSS slide out navigations are stupidly simple. Here is the crudest example (demo) :

<input id="hidden-trigger" type="checkbox">
<label for="hidden-trigger">click me</label>

<div class="hidden-menu">
DERP
</div>

<main>
<p>
This is the stuff you want visible all the time.
  </p>
</main>

and the CSS

#hidden-trigger{
  display: none;
}


div.hidden-menu{
  top: 0;
  width: 200px;
  right: -200px;
  position: absolute;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  transition: 0.2s right;
}

#hidden-trigger:checked ~ div.hidden-menu{
  right: 0;
}
/* demo has additional styles here for making it look nice */ 

Mechanics

There are two mechanics at work here: The first is the hidden checkbox. The label is the thing that remains visible and clickable and this causes the checkbox to alter state.

<input id="hidden-trigger" type="checkbox">
<label for="hidden-trigger">click</label> 

The second part of this is the altering of state of the checkbox, which is used as a trigger to change styles in the css

/* unchecked style */
div.hidden-menu{ 
   top: 0;
   width: 200px;
   right: -200px;

   /* this and the above width value must match */ 
   position: absolute;
   height: 100%;
   background-color: rgba(0, 0, 0, 0.3);
   transition: 0.2s right;
}

/* when checked,  change the right value -  transition kicks in & slides the nav*/

#hidden-trigger:checked ~ div.hidden-menu{
   right: 0; 
}

It really is as simple as that. I’ve not checked this in a range of browsers, so I cannot claim it is production ready but I can see no reason why it should be an issue. The main parts (sibling selector and transition) both enjoy excellent browser support.