css - 'height: fit-content' 没有 CSS 过渡
问题描述
我使用向通过按钮从到transition: height 500ms
滑动打开的元素添加动画,反之亦然。height: 0
height: 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>
解决方案
一种可能的解决方案,虽然不是完美的,是动画font-size
而不是height
.
另一种解决方案可能是动画max-height
而不是height
. 您可以使用max-height
300 像素或 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>
推荐阅读
- mysql - 将 CSV 数据作为块上传 Laravel
- office-js - 从服务器或本地计算机打开现有文档?
- mysql - 如何创建条件来自两个表的过程?
- angular - 如何使用 HighCharts 在点击事件上调用 EventEmitter
- windows - 退出/从睡眠模式重新启动时 CPU 消耗高(Windows 10)
- php - 隐藏或排除前端表单中的 ACF 字段并存储默认值
- php - Laravel 路由不使用参数
- flutter - AnimatedCrossFade 淡出然后淡入
- android - 本机库总是捕获错误 plugin_not_installed ionic3
- vue.js - 如何在外部 js 文件中使用 Vue.js