How to add a CSS3 transition to a child element when the parent is hovered

Soma M. picture Soma M. · Jul 5, 2013 · Viewed 19.2k times · Source
<!doctype html>
<html>
 <head>
   <meta charset="utf-8">
   <title>CSS Transition</title>
   <style>
     .child{ display: none; }
     .parent:hover > .child{ display: block; }
   </style>
 </head>
 <body>
  <div class="parent">
   <div class="child">Content</div>
  </div>
 </body>
</html>

I have created a simple layout above that shows the concept of what I am trying to achieve. What I want to do now is to make a CSS3 transition that will allow the child to ease in when the parent is hovered. However, I do not know where to place the transition code so it will work.

Answer

Derek Story picture Derek Story · Jul 5, 2013

For the child div that is hidden, use height: 0; and overflow: hidden; instead of display: none;, Then add a specified height on the child shown when hovered. This will allow for the transition to take place.

I would do something like this: http://jsfiddle.net/atjG8/1/

.parent {
    background: red;
}
.child {
    overflow: hidden;
    height: 0;
    background: blue;
    -webkit-transition: all .8s ease;
    -moz-transition: all .8s ease;
    -ms-transition: all .8s ease;
    -o-transition: all .8s ease;
    transition: all .8s ease;
    color: white;
}
.parent:hover > .child {
    height: 30px;
    display: block;
}

Colors were added for example...