One pure CSS solution is to use transform
.
element
{
position: relative;
top: 50%;
transform: translateY(-50%);
}
Notes:
- You can use
top: 50%;
for vertical andleft: 50%;
for horizontal. - You would then use
translateY(-50%)
for vertical andtranslateX(-50%)
for horizontal centering. - You can also use this trick to align elements to the bottom or right of it’s parent, like in a
table-cell
by using100%
instead of50%
in the css. - If you want to support older browsers, then you’ll need to use prefixes for
transform
. I highly recommend autoprefixer in your workflow.