What is CSS Margin Auto?

Introduction

CSS (Cascading Style Sheets) is a language used for describing the presentation of documents written in a markup language. One of the properties available in CSS is the margin property, which is used to control the spacing around an element. The margin property can be used to specify the size of the margins around an element, but it can also be set to auto to automatically center an element within its parent container.

What is CSS Margin Auto?

The margin: auto property is used to center an element horizontally within its parent container. When an element's margin-left and margin-right are set to auto, the browser calculates the left and right margins so that the element is centered within its parent container. The element will be centered horizontally regardless of the width of the parent container or the width of the element.

For example, if we have a div with a width of 600px and margins set to 0 auto, it will be centered within a parent container that is 1200px wide. Similarly, if the same div is placed within a parent container that is 800px wide, it will still be centered within the container.

div {
  width: 600px;
  margin: 0 auto;
}

Example

Here's an example of using margin: auto to center a div element within a parent container.

HTML:

<div class="container">
  <div class="inner-div">
    I am centered!
  </div>
</div>

CSS:

.container {
  width: 800px;
  border: 1px solid black;
}

.inner-div {
  border: 1px solid black;
  padding: 5px;
  width: 400px;
  margin: 50px auto;
}

In this example, the inner-div element is given a width of 400px and the margin property is set to 50px auto. This centers the inner-div element within the container element, which has a width of 800px. And also give a margin of 50px from the top and bottom. Below is the output:

See the Pen css margin auto by Vinish Kapoor (@foxinfotech) on CodePen.

Note

It's important to note that margin: auto will only center an element horizontally, not vertically. If you want to center an element both horizontally and vertically, you will need to use other techniques, such as positioning and transforms.

Also when you set the margin: auto on an element it will only center the element if the element has a set width or max-width.

You can also use the justify-content: center and align-items: center to center element inside flex container.

Related: