css - 如何过渡高度 : 0; to height: auto; using CSS?

标签 css css-transitions

我正在尝试制作 <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>

最佳答案

在转换中使用 max-height 而不是 height。并将 max-height 的值设置为比您的盒子所能达到的更大的值。

参见 JSFiddle demo由 Chris Jordan 在另一个 answer 中提供在这里。

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

关于css - 如何过渡高度 : 0; to height: auto; using CSS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3149419/

相关文章:

html - CSS 过渡 parent 以匹配 child 的最终高度

html - 宽度过渡 - 直接选择过渡以增加和减少宽度

javascript - 将鼠标悬停在页面顶部以显示菜单

html - 如何在 CSS 对 Angular 切片中创建以图像为背景的卡片

javascript - 删除一个时如何在 Vue 中为列表项设置动画

html - CSS3 3D Transitions 在使用 box-shadow 时在 firefox 中闪烁

css,不同类的反向转换

javascript - 防止过渡变换比例上的边界模糊

javascript - 检索内联元素相对于父文本行的位置和尺寸

php - WordPress query_var 按域