To center an element, apply and margin of auto. Alternatively, use a display of flex, with content center-justified or grid, with content placed in the center.
There are several ways to center an element using CSS, and the best method to use depends on the given context.
The simplest way to center an element is to use margin auto:
margin: auto;
Margin auto will automatically apply an equal margin to both the left and right side of the element, thereby positoning the element in the center of its container.
This method of centering is well suited for page content with a maximum width. As the window expands beyond the max width, the page content should not get any wider but be kept in the center of the container.
Another way to center a div is to use flexbox:
display: flex;
justify-content: center;
This method is better suited for containers which have multiple elements. The elements will be evenly distributed along the flex axis (horizontal by default) and centered appropriately.
Using grid:
display: grid;
place-content: center;
This method is a quick and dirty way to position a single element in the center of a container without worrying about margins.
A bonus method using text alignment:
text-align: center;
This method is most appropriate if your element only contains text and you simply want to justify the text to the center.