当max-height从0增加时,最大高度的CSS过渡并不容易(纯CSS)

时间:2016-03-09 01:36:38

标签: html css

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

  2. 此外,除了使用max-height之外,还有更好的方法吗?我将max-height设置为1000px。我希望它能够自动扩展到它所需的高度,而无需我选择随机值。

  3. 感谢您的帮助!

    
    
    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>
    &#13;
    &#13;
    &#13;

1 个答案:

答案 0 :(得分:1)

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

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