margin: auto
![Using margin: auto for Centering in CSS](/_next/image/?url=https%3A%2F%2Fstatic.d-libro.com%2F01-course-content-images%2F1011-10-HTML-CSS-Introduction%2F010-main-figures%2Fmargin-auto-id101110100610.webp&w=1920&q=75)
Unlike for padding
, you can use auto
as a keyword for the margin
property value. When you use auto
, the browser tries to maximize margins as much as possible.
For example, in the case like in the illustration below,
![A HTML child element position without margin: auto A HTML child element position without margin: auto](https://static.d-libro.com/01-course-content-images/1011-10-HTML-CSS-Introduction/020-image-insert/a-html-child-element-position-without-margin-auto-id101110100610-img01.webp)
when you set margin: auto
for the child element, the auto value tries to maximize the margin for both sides. As a result, the child element is placed in the center of the parent element horizontally.
![A HTML child element position with margin: auto A HTML child element position with margin: auto](https://static.d-libro.com/01-course-content-images/1011-10-HTML-CSS-Introduction/020-image-insert/a-html-child-element-position-with-margin-auto-id101110100610-img02.webp)
When you set margin-left: auto
for the child element, the auto value tries to maximize the left side of the margin. As a result, the child element is pushed to the right edge of the parent element.
![A HTML child element position with margin-left: auto A HTML child element position with margin-left: auto](https://static.d-libro.com/01-course-content-images/1011-10-HTML-CSS-Introduction/020-image-insert/a-html-child-element-position-with-margin-left-auto-id101110100610-img03.webp)
margin: auto with Flex Box
In the regular situation, margin: auto
works only horizontally; however, when the parent element is set as a Flex Box, the auto
keyword works for both horizontal and vertical dimensions. We'll explain how margin: auto
works with Flex Box later.