css3 transition from width auto to “n” px [duplicate]

孤街浪徒 提交于 2019-12-01 14:45:53

by default min-width will take inside element 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>

Instead of animating width try animating min-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>

It is impossible to run an animation from auto to Npx, due to the way animations are constructed.

For example, take this CSS:

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

This would esentialy be the same as the following code:

@keyframes animate-width {
    from { width: 100px; }
    to { width: 200px; }
}

.block {
    width: 100px;
 }

 .block:hover {
     animate: animate-width 2s;
 }

As you can see from the animation keyframes, a startpoint and an endpoint are defined in order to be able to create a proper animation.

In order to run an animation a start and endpoint have to be available for the browser's CSS rendering engine to function properly. auto can never be a start point, since it's a dynamically assigned value.

You may be able to use Javascript to make this work, by setting the proper width after loading the page. For block elements, setting the width to 100% instead of auto may work as a solution as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!