Learning While Aging

Using CSS Margin Auto May Cause CSS Transitions Not To Work

The CSS transitions and transformations make it very easy to change different properties of an element on a web page and to apply those changes without using JavaScript. For instance, we can use simple CSS transitions to move a <div> box slowly to the right side of a window when the mouse hovers over the window, as shown in this code snippet:

See the Pen A simple moving box by Jeffrey (@NTOTL) on CodePen.

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:

See the Pen A simple moving box with no transition by Jeffrey (@NTOTL) on CodePen.

So what had happened? Well, it turned out that it is not recommended to use the CSS transitions on properties with “auto” values:


The auto value 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 auto may lead to unpredictable results, depending on the browser and its version, and should be avoided.


https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Transitions/Using_CSS_transitions#Which_CSS_properties_can_be_transitioned

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!