小编典典

如何转换高度:0; 达到高度:自动;使用CSS?

css

我正在尝试<ul>使用CSS过渡制作幻灯片。

<ul>在开始关闭height: 0;。悬停时,高度设置为height:auto;。但是,这导致它只是显示 而不是 过渡,

如果我从height: 40px;到进行操作height: auto;,则它将向上滑动到height: 0;,然后突然跳到正确的高度。

不使用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.

<hr>

<div id="parent0">

  <h1>Hover me (height: 0)</h1>

  <div id="child0">Some content

    <br>Some content

    <br>Some content

    <br>Some content

    <br>Some content

    <br>Some content

    <br>

  </div>

</div>

<hr>

<div id="parent40">

  <h1>Hover me (height: 40)</h1>

  <div id="child40">Some content

    <br>Some content

    <br>Some content

    <br>Some content

    <br>Some content

    <br>Some content

    <br>

  </div>

</div>

阅读 279

收藏
2020-05-16

共1个答案

小编典典

max-height在过渡中使用,而不是height。并设置一个max-height比您的盒子所能获得的更大的价值。

#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;

}


<div id="menu">

    <a>hover me</a>

    <ul id="list">

        <!-- Create a bunch, or not a bunch, of li's to see the timing. -->

        <li>item</li>

        <li>item</li>

        <li>item</li>

        <li>item</li>

        <li>item</li>

    </ul>

</div>
2020-05-16