html - 当最大高度从 0 增加时,最大高度上的 CSS 过渡不会缓解(纯 CSS)

标签 html css

  1. 有人能告诉我为什么当最大高度变为 0 时动画可以正常工作,反之则不能吗?当 max-height 设置为 1000px 时,列表会快速打开而不是缓入。我正在尝试仅使用 CSS 来实现此动画。

  2. 此外,除了使用最大高度之外,是否有更好的方法来做到这一点。我将最大高度设置为 1000 像素。我希望它自动扩展到所需的高度,而无需我选择随机值。

感谢您的帮助!

body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: white;
}

.accordion .tab {
  margin-bottom: 1px;
}
.accordion .tab input[type="checkbox"] {
  display: none;
}
.accordion .tab input[type="checkbox"] + label {
  display: block;
  height: 50px;
  width: 300px;
  text-align: center;
  background: blue;
  line-height: 50px;
  color: white;
  margin-bottom: 1px;
}
.accordion .tab input[type="checkbox"] ~ ul {
  max-height: 1000px;
  transition: max-height .5s ease;
}
.accordion .tab input[type="checkbox"]:checked ~ ul {
  max-height: 0;
  overflow: hidden;
  transition: max-height .5s ease;
}
.accordion .tab ul {
  padding: 0;
  margin: 0;
}
.accordion .tab ul li {
  list-style-type: none;
  height: 50px;
  width: 300px;
  background: green;
  margin-bottom: 1px;
}
<div class="accordion">
  <div class="tab">
    <input type="checkbox" id="tab1">
    <label for="tab1">Cars</label>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
  <div class="tab">
    <input type="checkbox" id="tab2">
    <label for="tab2">Trucks</label><ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
    </ul>
  </div>
</div>

最佳答案

  1. 当您transitionmax-height: 1000px; 时,过渡假定元素的高度将是 1000px,因此过渡必须在 .5s 中覆盖 1000px。当你转换回 0 时,它已经知道实际高度,所以它只需要在 .5s 中将该高度(比如 300px)转换回 0px,这会慢两倍以上。

  2. 您可以通过指定较小的最大高度来减慢它的速度。至于所使用的方法,如果您需要它来过渡动态高度,您将使用唯一的 css 解决方案。您可以考虑使用 JS/Jquery 解决方案来计算高度,然后对其进行转换。

关于html - 当最大高度从 0 增加时,最大高度上的 CSS 过渡不会缓解(纯 CSS),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881374/

相关文章:

javascript - 检测并替换 contenteditable div 上光标之前的单词

jquery - 溢出 :auto in jqgrid not working after upgrading jquery from 1. 6.2 到 3.2.1

javascript - HTML5 不加载隐藏的 div?

javascript - 我不希望弹出窗口在用户点击离开时最小化

jquery - .悬停功能不起作用

java - 如何在表vaadin中设置复选框的大小

html - 更新样式表和缓存中引用的图像

HTML 和 CSS 大小调整

html - 错误消息跨度中的 css 间距

html - CSS/HTML : a tag with a span inside, 跨边距在悬停下划线上创建空白