23 July 2015

CSS3 Drop Menu Fade In

The Basics

I have an HTML menu:

UL - top menu
  LI - first item
    A
    UL - sub menu
      LI - first sub item
        A 

and some basic CSS:

#menu li ul {
  display: none;
}

#menu li:hover > ul {
  display: block;
}

So when we hover over the first item, the sub-menu appears.  Simples.


Fade-in using transition

I wanted to make the menu fade in using the lovely new css transition attribute, and I thought by adding an opacity attribute it would, appear then fade in.

#menu li ul {
     display: none;
     opacity: 0;
  transition: opacity .25s;
}

#menu li:hover > ul {
  display: block;
  opacity: 1;
}

So in theory when we hover the display is changed to block, and the opacity will fade the menu in a .25 seconds.

It doesn't work however, using the display attribute breaks the transition, no idea why but it does.

CSS animate to the rescue

We can make it work using the animate property and a keyframes block.

@keyframes fadein {
    0% { opacity: 0; }
  100% { opacity: 1; }
}

#menu li ul {
    display: none;
    opacity: 0;
  animation: fadein .25s;
}

#menu li:hover > ul {
  display: block;
  opacity: 1;
}

There is one drawback with this method however,  we can't do a fadeout, because the display:hidden happens at the start of the animation, not a the end, which is what we want to happen in a fadeout. 

Thanks to Hermann Schwarz for the idea.

No comments: