Can I apply animations to margins?

denislexic picture denislexic · May 14, 2015 · Viewed 49.1k times · Source

I'm trying to animate in CSS3 margins, which this site seems to say you can, but I can't get working.

I actually have 3 animations. 1 for a simple initial fadeIn on initial load, then the 2 others for the margin animation on click. I've also just tried margin instead of the top and bottom but still no sign of it working.

Click on a section to see animation toggle.

Here is a JSFiddle: http://jsfiddle.net/ybh0thp9/3/

Answer

Bram Vanroy picture Bram Vanroy · May 14, 2015

You don't need keyframes for this: http://jsfiddle.net/BramVanroy/ybh0thp9/7/

transition: margin 700ms;

You need to add the transition property to the base element that you wish to animate.

You also mentioned that you wanted opacity change, but I don't see how that's possible considering you only have a single element without children. I mean: you can't click on the element if it's hidden.

What you can do, though, is add opacity to the whole thing: http://jsfiddle.net/BramVanroy/ybh0thp9/9/

Or even prettier, with a transformation:

http://jsfiddle.net/BramVanroy/ybh0thp9/10/

.section {
    margin: 0;
    opacity: 0.7;
    transform: scale(0.85);
    transition: all 700ms;
}
.section.open {
    margin: 20px 0;
    opacity: 1;
    transform: scale(1);
}

Per comment, you want to fade in the elements on page load. We can do that by adding a class init.

http://jsfiddle.net/BramVanroy/ybh0thp9/12/

$(".section").addClass("init"); // JS
.section.init {opacity: 1;} // CSS

With keyframes: http://jsfiddle.net/BramVanroy/ybh0thp9/14/

@-webkit-keyframes fadeIn { from {opacity: 0; } to { opacity: 1; } }
@-moz-keyframes fadeIn { from {opacity: 0; } to { opacity: 1; } }
@keyframes fadeIn { from {opacity: 0; } to { opacity: 1; } }

-webkit-animation: fadeIn 1.5s ease;    
-moz-animation: fadeIn 1.5s ease;
animation: fadeIn 1.5s ease;