Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Role of margin property with value auto using CSS
The CSS margin property with value auto is used to horizontally center block-level elements within their container. When you set left and right margins to auto, the browser distributes the available space equally on both sides, creating a centered effect.
Syntax
selector {
margin: auto;
}
/* Or specifically for horizontal centering */
selector {
margin-left: auto;
margin-right: auto;
}
How It Works
For margin: auto to work effectively for centering, the element must have a defined width and be a block-level element. The browser calculates the remaining horizontal space and divides it equally between the left and right margins.
Example: Centering a Block Element
The following example demonstrates how to center a div element using margin: auto −
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 100%;
background-color: #f0f0f0;
padding: 20px;
}
.centered-box {
width: 300px;
height: 100px;
margin: auto;
background-color: #4CAF50;
border: 2px dashed blue;
display: flex;
align-items: center;
justify-content: center;
color: white;
font-weight: bold;
}
.normal-text {
margin-bottom: 20px;
}
</style>
</head>
<body>
<div class="container">
<p class="normal-text">This is demo text</p>
<div class="centered-box">
Horizontally Centered with margin: auto
</div>
</div>
</body>
</html>
A gray container appears with demo text at the top, followed by a green box with blue dashed border that is horizontally centered. The box contains white text "Horizontally Centered with margin: auto".
Key Points
- The element must have a defined width for
margin: autoto center it horizontally - Only works for horizontal centering − vertical centering requires different techniques
- The element should be a block-level element or have
display: block
Conclusion
The margin: auto property is the most common and reliable method for horizontally centering block elements. It automatically distributes available horizontal space equally on both sides of the element, creating perfect horizontal alignment.
