How can you center a <div> both vertically and horizontally using Flexbox?</div>
•13 min read
Here’s how you can center a <div> both vertically and horizontally using Flexbox — the modern, responsive, and clean way to align elements.
✅ Example Code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center a Div with Flexbox</title>
<style>
body {
margin: 0;
height: 100vh; /* full viewport height */
display: flex; /* enable flexbox */
justify-content: center; /* horizontal centering */
align-items: center; /* vertical centering */
background-color: #f4f4f4;
font-family: Arial, sans-serif;
}
.center-box {
width: 200px;
height: 150px;
background-color: #3498db;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
}
</style>
</head>
<body>
<div class="center-box">
Centered Box
</div>
</body>
</html>
JavaScript🧠 How It Works
| CSS Property | Purpose |
|---|---|
display: flex; | Turns the container (body) into a flexbox. |
justify-content: center; | Centers content horizontally. |
align-items: center; | Centers content vertically. |
height: 100vh; | Makes the container the full viewport height so vertical centering works perfectly. |
⚙️ Alternative (if you want to center inside another div)
.parent {
display: flex;
justify-content: center;
align-items: center;
height: 400px;
background: #eee;
}
.child {
background: #4caf50;
padding: 20px;
color: white;
}
JavaScript<div class="parent">
<div class="child">Centered Div</div>
</div>JavaScript

