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
How to center an element vertically and horizontally with CSS?
To center an element vertically and horizontally with CSS, use the justify-content and align-items properties with flexbox. This is one of the most reliable and modern methods for achieving perfect centering.
Syntax
selector {
display: flex;
justify-content: center;
align-items: center;
}
The Justify-content Property
In CSS, the justify-content property is used to align flex items horizontally along the main axis. The syntax is as follows −
selector {
display: flex;
justify-content: value;
}
The following are the possible values −
flex-start − The flex items are positioned at the start of the container (default)
flex-end − The flex items are positioned at the end of the container
center − The flex items are positioned in the center of the container
space-between − The flex items have space between them
space-around − The flex items have space before, between, and after them
space-evenly − The flex items have equal space around them
The Align-items Property
In CSS, the align-items property is used to align flex items vertically along the cross axis. The syntax is as follows −
selector {
display: flex;
align-items: value;
}
The following are the possible values −
stretch − The flex items are stretched to fit the container (default)
center − The flex items are positioned at the center of the container
flex-start − The flex items are positioned at the beginning of the container
flex-end − The flex items are positioned at the end of the container
Example: Perfect Centering with Flexbox
The following example demonstrates how to center an element both vertically and horizontally using flexbox −
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 0;
}
.centered {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
border: 3px solid rgb(0, 70, 128);
background-color: #f0f8ff;
}
.content {
background-color: #4CAF50;
color: white;
padding: 20px;
border-radius: 8px;
text-align: center;
}
</style>
</head>
<body>
<div class="centered">
<div class="content">
<h2>Perfectly Centered!</h2>
<p>This content is centered both vertically and horizontally.</p>
</div>
</div>
</body>
</html>
A light blue container with a blue border appears. Inside it, a green rounded box with white text is perfectly centered both vertically and horizontally, containing the heading "Perfectly Centered!" and a descriptive paragraph.
Conclusion
Using flexbox with justify-content: center and align-items: center is the most reliable modern method for centering elements both vertically and horizontally. This approach works consistently across all modern browsers and handles content of any size.
