首页 > 解决方案 > 'height: fit-content' 没有 CSS 过渡

问题描述

我使用向通过按钮从到transition: height 500ms滑动打开的元素添加动画,反之亦然。height: 0height: 100px

由于元素的内容是动态添加的,而且我不知道它的大小,我想改用它height: fit-content。这样,元素将始终具有正确的大小来显示其内容。

可悲的是,这会禁用动画。

如何将动画与大小适合其内容的 div 元素放在一起?

以下片段显示了行为:

document.querySelector('button')
  .addEventListener(
    'click',
    () => document.querySelectorAll('div')
      .forEach(div => div.classList.toggle('closed')));
div {
  background-color: lightblue;
  border: 1px solid black;
  overflow: hidden;
  transition: height 500ms;
}

div.closed {
  height: 0 !important;
}

div.div1 {
  height: 100px;
}

div.div2 {
  height: fit-content;
}
<button type="button">toggle</button>

<h1>'height: 100px' => 'height: 0'</h1>
<div class="div1">
some text<br />
even more text<br />
so much text
</div>

<br>

<h1>'height: fit-content' => 'height: 0'</h1>
<div class="div2">
some text<br />
even more text<br />
so much text
</div>

标签: cssanimationcss-transitionstransitionslide

解决方案


一种可能的解决方案,虽然不是完美的,是动画font-size而不是height.

另一种解决方案可能是动画max-height而不是height. 您可以使用max-height300 像素或 500 像素。但如果你需要更多,它看起来不会很好。

在这里,我正在为字体大小设置动画。

希望有帮助。谢谢。

document.querySelector('button')
  .addEventListener(
    'click',
    () => document.querySelectorAll('div')
      .forEach(div => div.classList.toggle('closed')));
div {
  background-color: lightblue;
  border: 1px solid black;
  overflow: hidden;
  transition: font-size 500ms;
}

div.closed {
  font-size: 0 !important;
}

div.div1 {
  font-size: 14px;
}

div.div2 {
  font-size: 14px;
}
<button type="button">toggle</button>

<h1>'height: 100px' => 'height: 0'</h1>
<div class="div1">
some text<br />
even more text<br />
so much text
</div>

<br>

<h1>'height: fit-content' => 'height: 0'</h1>
<div class="div2">
some text<br />
even more text<br />
so much text
</div>


推荐阅读