你可以使用CSS3从height:0过渡到内容的可变高度吗?

14 浏览
0 Comments

你可以使用CSS3从height:0过渡到内容的可变高度吗?

我正在尝试使用CSS过渡使

    • 滑动下来。

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.

 

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

admin 更改状态以发布 2023年5月22日
0
0 Comments

你应该使用scaleY。

ul {
  background-color: #eee;
  transform: scaleY(0);    
  transform-origin: top;
  transition: transform 0.26s ease;
}
p:hover ~ ul {
  transform: scaleY(1);
}


Hover This

  • Coffee
  • Tea
  • Milk

我在jsfiddle上制作了一个使用供应商前缀的代码版本,并将你的jsfiddle改为使用scaleY而不是height。

编辑
有些人不喜欢scaleY如何转换内容。如果有问题,我建议使用clip

ul {
  clip: rect(auto, auto, 0, auto);
  position: absolute;
  margin: -1rem 0;
  padding: .5rem;
  color: white;
  background-color: rgba(0, 0, 0, 0.8);
  transition-property: clip;
  transition-duration: 0.5s;
  transition-timing-function: cubic-bezier(0.175, 0.885, 0.32, 1.275);
}
h3:hover ~ ul,
h3:active ~ ul,
ul:hover {
  clip: rect(auto, auto, 10rem, auto);
}


Hover here

  • This list
  • is clipped.
  • A clip transition
  • will show it

Some text...

0
0 Comments

在过渡效果中使用max-height而不是height,并给max-height设置一个比你的盒子预计最大值更大的值。
可以查看Chris Jordan在这个回答中提供的JSFiddle演示

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


    hover me
    
  • item
  • item
  • item
  • item
  • item

0