【问题标题】:css3 transition from width auto to "n" px [duplicate]css3从宽度自动过渡到“n”像素[重复]
【发布时间】:2016-03-22 08:39:12
【问题描述】:

如何将 css 过渡应用到初始宽度设置为 auto 的 div

但是,如果我将初始宽度设置为某个数字(例如 50 像素),就会开始过渡。

这里是-DEMO

.container {
  width: 200px;
  background: red;
  height: 50px;
}


.child1 {
  background: black;
  display: inline-block;

}

.child2 {
  background: blue;
    display: inline-block;
  width: auto;  /* this does not work */

    /* width: 50px; */ /* this works */
  float: right;
  -webkit-transition: width 2s;
      transition: width 2s;
}

.child2:hover {
  width: 100px;
}

【问题讨论】:

  • 这是一个已知(和预期)的行为。您不能从/到自动转换。
  • 唯一的办法就是使用 JavaScript。

标签: css css-transitions


【解决方案1】:

默认情况下min-width 将采用内部元素width

.container {
  width: 200px;
  background: red;
  height: 50px;
}
.child1 {
  background: black;
  display: inline-block;
}
.child2 {
  background: blue;
  display: inline-block;
  width: auto;
  min-width: 0px; /*changed width to min-width */
  float: right;
  -webkit-transition: 2s;
  transition: 2s;
}
.child2:hover {
  min-width: 100px; /* changed from width to min-width */
}
<div class="container">
  <div class="child1">
    child1
  </div>
  <div class="child2">
    child2
  </div>
</div>

【讨论】:

    【解决方案2】:

    尝试为min-width 设置动画,而不是为width 设置动画:

    .container {
      width: 200px;
      background: red;
      height: 50px;
    }
    .child1 {
      background: black;
      display: inline-block;
    }
    .child2 {
      background: blue;
      display: inline-block;
      width: auto;
      /* this does not work */
      min-width: 0;
      float: right;
      -webkit-transition: all .5s;
      transition: all .5s;
      padding-left: 0;
    }
    .child2:hover {
      min-width: 100px;
    }
    <div class="container">
      <div class="child1">
        child1
      </div>
    
      <div class="child2">
        child2
      </div>
    </div>

    【讨论】:

      【解决方案3】:

      由于动画的构造方式,无法从autoNpx 运行动画。

      以这个 CSS 为例:

      .block {
          width: 100px;
          transition: width 2s;
      }
      .block:hover {
          width: 200px;
       }
      

      这基本上与以下代码相同:

      @keyframes animate-width {
          from { width: 100px; }
          to { width: 200px; }
      }
      
      .block {
          width: 100px;
       }
      
       .block:hover {
           animate: animate-width 2s;
       }
      

      从动画关键帧中可以看出,定义了起点和终点以便能够创建适当的动画。

      为了运行动画,浏览器的 CSS 渲染引擎必须有一个起点和终点才能正常运行。 auto 永远不能作为起点,因为它是一个动态分配的值。

      您可以使用 Javascript 来完成这项工作,方法是在加载页面后设置适当的宽度。对于块元素,将宽度设置为 100% 而不是 auto 也可以作为一种解决方案。

      【讨论】:

        猜你喜欢
        • 2013-01-31
        • 2013-02-01
        • 1970-01-01
        • 2014-02-04
        • 2013-04-02
        • 2015-08-01
        • 1970-01-01
        • 2015-06-20
        • 2014-04-10
        相关资源
        最近更新 更多