In the above example, the box starts at the very left side of the window and moves all the way to the right size of the window when the mouse hovers over it. What if we want the box starts from the middle of the window and moves all the way to the right side of the window? OK, let’s give it a try.
First, we need to place the box in the middle of the window. The easiest way is to use automatic margins with fixed width, as follows:
width: 45px; height: 45px; margin: auto; /* add this line to make the box stay in the middel of the window */
However, when the mouse hovers over the window, you will notice the box will move to the right side of the window immediately. There is no transition effect at all, as shown below:
So what had happened? Well, it turned out that it is not recommended to use the CSS transitions on properties with “auto” values:
autovalue is often a very complex case. The specification recommends not animating from and to
auto. Some user agents, like those based on Gecko, implement this requirement and others, like those based on WebKit, are less strict. Using animations with
automay lead to unpredictable results, depending on the browser and its version, and should be avoided.
OK, now we know we cannot use “margin: auto” to place the box in the middle of the window without losing the transition effect, then is there a workaround? The answer is yes and we can use half of the viewport to place the box in the middle, as shown below:
width: 45px; height: 45px; margin-left: 50vw;
Now, if you hover the mouse over the window, the middle box will slowly move to the right side of the window, just the way we want it. Mission Accomplished!