Centering elements is one of the first challenges beginner developers face. Whether it’s a login form, a button, or a section of your layout, learning how to center a div with CSS is an essential skill.
In this tutorial, you’ll learn the most common and modern ways to center a div, both horizontally and vertically, using flexbox, grid, and traditional techniques — step by step.
👁️ Preview
🧱 Basic HTML Structure
We’ll use this simple div
to demonstrate all methods:
<div class="container">
<div class="box">Centered Box</div>
</div>
Now let’s explore the different ways to center .box
inside .container
.
🎯 Method 1: Center with Flexbox
✅ Best for modern layouts
.container {
display: flex;
justify-content: center; /* horizontal */
align-items: center; /* vertical */
height: 100vh;
background: #f0f0f0;
}
.box {
padding: 2rem;
background: #7179F4;
color: white;
border-radius: 8px;
}
✔️ Why it works:
display: flex
enables flexbox layoutjustify-content
centers horizontallyalign-items
centers verticallyheight: 100vh
makes the container full screen
🔲 Method 2: Center with CSS Grid
✅ Clean and powerful for full-page layouts
.container {
display: grid;
place-items: center;
height: 100vh;
}
.box {
padding: 2rem;
background: #525174;
color: white;
border-radius: 8px;
}
✔️ Why it works:
place-items: center
is a shorthand for centering both axes in a grid
📏 Method 3: Center Horizontally with Margin Auto
✅ Old school, still useful
.container {
width: 100%;
}
.box {
width: 300px;
margin: 0 auto;
}
✔️ Why it works:
margin: 0 auto
centers the box horizontally within the container
📐 Method 4: Center with Position + Transform
✅ Compatible with older browsers
.container {
position: relative;
height: 100vh;
}
.box {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
✔️ Why it works:
- Moves the element 50% from the top and left
transform: translate
pulls it back by 50% of its own size
✅ Final Result
Each method has its best use case:
- Flexbox: general-purpose layouts
- Grid: full-screen centering
- Margin auto: horizontal centering only
- Position + transform: older projects
Choose the one that fits your project — all of them are valid and useful.
🔧 Bonus Tip: Responsive Container
Make sure your .container
has a defined height (like 100vh
or a parent height), or vertical centering won’t work as expected!