Centering elements with CSS

Last modified March 10, 2019
.* :☆゚

There are many different ways to center content with CSS.

Relative positioned elements and elements not spanning 100% width usually only need the following:

position: relative;
margin : auto;
display: table;

Absolutely positioned elements require a bit more code wrangling.

Center an element horizontally:

position: absolute;
margin-left: auto;
margin-right: auto;
left: 0;
right: 0;

Center an element horizontally and vertically:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);