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
Selected Reading
Center alignment using the margin property in CSS
We can center horizontally a block-level element by using the CSS margin property, but CSS width property of that element should be set. The auto value is set for the margin property.
Syntax
selector {
margin: top-bottom-value auto;
width: value;
}
The key points for center alignment using margin are −
- Set a specific width on the element
- Use
margin: autoormargin: value auto - The element must be a block-level element
Example: Center a Simple Div
Let's see a basic example of centering a div using the margin property −
<!DOCTYPE html>
<html>
<head>
<style>
.centered-box {
width: 300px;
height: 100px;
margin: 20px auto;
background-color: #4CAF50;
color: white;
text-align: center;
line-height: 100px;
border: 2px solid #000;
}
</style>
</head>
<body>
<div class="centered-box">Centered Box</div>
</body>
</html>
A green box with "Centered Box" text appears horizontally centered on the page with a black border.
Example: Center Multiple Divs with Different Widths
In this example, we have centered multiple divs with different widths using the margin property −
<!DOCTYPE html>
<html>
<head>
<style>
.screen {
padding: 15px;
margin: 10px auto;
text-align: center;
color: white;
border-radius: 0 0 25px 25px;
border: 3px solid #000;
}
.screen1 {
background-color: #f06d06;
width: 70%;
}
.screen2 {
background-color: #48C9B0;
width: 50%;
}
.screen3 {
background-color: #DC3545;
width: 30%;
}
</style>
</head>
<body>
<div class="screen screen1">Screen 70%</div>
<div class="screen screen2">Screen 50%</div>
<div class="screen screen3">Screen 30%</div>
</body>
</html>
Three centered boxes appear with different widths: orange box (70%), teal box (50%), and red box (30%), all with rounded bottom corners and center-aligned text.
Key Points
| Property | Required Value | Purpose |
|---|---|---|
width |
Specific value (px, %, em) | Defines element width |
margin |
auto (left and right) | Centers the element |
display |
block (default for div) | Must be block-level element |
Conclusion
The CSS margin property with auto value is the most reliable method for horizontal centering of block-level elements. Remember to always set a specific width for the element you want to center.
Advertisements
