如何使用CSS将高度从0过渡到自适应高度?

25 浏览
0 Comments

如何使用CSS将高度从0过渡到自适应高度?

我正在尝试使用CSS transitions让

    • 下拉。

    • 一开始的高度为

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月21日
0
0 Comments

你应该使用scaleY而不是height。

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