Monday 3 April 2017

How can I transition height: 0; to height: auto; using CSS?



I am trying to make a

    slide down using CSS transitions.



    The

      starts off at height: 0;. On hover, the height is set to height:auto;. However, this is causing it to simply appear, not transition,



      If I do it from height: 40px; to height: auto;, then it will slide up to height: 0;, and then suddenly jump to the correct height.




      How else could I do this without using JavaScript?





      #child0 {
      height: 0;
      overflow: hidden;
      background-color: #dedede;
      -moz-transition: height 1s ease;
      -webkit-transition: height 1s ease;

      -o-transition: height 1s ease;
      transition: height 1s ease;
      }
      #parent0:hover #child0 {
      height: auto;
      }
      #child40 {
      height: 40px;
      overflow: hidden;
      background-color: #dedede;

      -moz-transition: height 1s ease;
      -webkit-transition: height 1s ease;
      -o-transition: height 1s ease;
      transition: height 1s ease;
      }
      #parent40:hover #child40 {
      height: auto;
      }
      h1 {
      font-weight: bold;

      }

      The only difference between the two snippets of CSS is one has height: 0, the other height: 40.



      Hover me (height: 0)


      Some content

      Some content

      Some content

      Some content

      Some content


      Some content






      Hover me (height: 40)


      Some content

      Some content

      Some content


      Some content

      Some content

      Some content






Answer




Use max-height in the transition and not height. And set a value on max-height to something bigger than your box will ever get.



See JSFiddle demo provided by Chris Jordan in another answer here.





#menu #list {
max-height: 0;
transition: max-height 0.15s ease-out;
overflow: hidden;

background: #d5d5d5;
}

#menu:hover #list {
max-height: 500px;
transition: max-height 0.25s ease-in;
}






No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...