I can see that this code works to align a div vertically within its parent element:
.element {
position: relative;
While others have provided the answer that the -50 moves the inner element back up half it's own height, I thought this little animation showing the movement to top: 50%;
first, followed by transform: translateY(-50%);
second, might help.
@keyframes centerMe {
0% { top: 0%; transform: translateY(0%); }
50% { top: 50%; transform: translateY(0%); }
100% { top: 50%; transform: translateY(-50%); }
}
.outer {
position: relative;
border: solid 1px;
height: 200px;
width: 200px;
}
.inner {
position: relative;
background-color: red;
height: 50px; width: 50px;
margin: auto;
animation: centerMe 5s;
animation-fill-mode: forwards;
}
/* rules for example */
.hline,.vline{background:#000;position:absolute}.vline{height:100%;width:1px;left:calc(50% - .5px);top:0}.hline{width:100%;height:1px;top:calc(50% - .5px)}