css3 transition from width auto to “n” px [duplica

2020-03-31 05:27发布

问题:

how do I apply css transition to a div which has initial width set as auto

However if I set the initial width to some number say 50px, the transition kicks in.

Here is the - 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;
}

回答1:

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>



回答2:

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>



回答3:

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.