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 toblock
orinline-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:
