Carlos Navarro Carlos Navarro - 4 months ago 11
CSS Question

Compatibility between translate(-50%, -50%) and animations

Having the following css:

.screen {
position: fixed;
width: 100%;
height: 100%;
}

.card {
width: 200px; background: #ccc;
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}

@keyframes kf_anim {
0% {
transform: rotateY(315deg);

}

100% {
transform: rotateY(360deg);
}
}

.card_anim {
animation: kf_anim 0.5s forwards;
}


If I do

<div class="screen">
<div class="card">content</div>
</div>


I get a horizontally-and-vertically centered div, which is what I want. But if I add the animation

<div class="screen">
<div class="card card_anim">content</div>
</div>


The animation is performed but the div is no longer centered, i.e., the translate(-50%, -50%) is overridden.

I tried adding
translate(-50%, -50%)
next to the
rotateY
in the keyframes, but then the animation does not work properly.

How can I solve this, assuming that I can't know the width and height?

JSFiddle: https://jsfiddle.net/n5pma29m/

Answer

You have to use the css combined like below

 @keyframes kf_anim {
        0% {
            transform: translate(-50%, -50%) rotateY(315deg);

        }

        100% {
            transform:translate(-50%, -50%) rotateY(360deg);
        }
    }

Updated fiddle here