Course Content
CSS Basic
0/1
CSS Selectors
0/1
CSS Comments
0/1
CSS Backgrounds
0/1
CSS Borders
0/1
CSS Outline
0/1
CSS Fonts
0/1
CSS Icons
0/1
CSS Links
0/1
CSS Lists
0/1
CSS Tables
0/1
CSS Display Properties
0/1
CSS Positioning Elements
0/1
CSS Z-Index Property
0/1
CSS Overflow
0/1
CSS Float
0/1
CSS Opacity
0/1
CSS Forms
0/1
CSS Dropdowns
0/1
CSS Buttons
0/1
CSS Media Queries
0/1
About Lesson

margin: auto;

Definition:

The margin: auto; property in CSS automatically sets equal left and right margins to center an element horizontally within its container.

How it Works:

  • It is mostly used to horizontally center block-level elements like <div>.
  • It only works if the element has a specified width (other than 100%).
  • It does not work on inline elements (like <span>) unless their display is changed to block or inline-block.

Syntax:

selector {
  width: value;
  margin: auto;
}

/*Applies to: Block-level elements like <div>, <section>, <p>, etc. */

Applies To:

  • Block-level elements like <div>, <section>, <p>, etc.
  • Inline elements only if their display is changed using:
    display: block; or display: inline-block;

Doesn’t work if:

  • The element has no width set.
  • The element is inline (like <span>) without changing its display.

Example:

HTML
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <style>
    .center-box {
      width: 300px;
      margin: auto;
      background-color: lightblue;
      border: 2px solid navy;
      padding: 20px;
      text-align: center;
    }
  </style>
  <title>Margin Auto Example</title>
</head>
<body>
  <div class="center-box">
    This box is horizontally centered using <code>margin: auto;</code>
  </div>
</body>
</html>

Output: