Tutorial 33 of 44 in series
CSS Centering
All the ways to center in CSS
Abhishek Sharma 2026-05-30 Web Development / Frontend / CSS
Centering
Centering is a common layout challenge. Here are the most reliable techniques:
Horizontal Centering
Demo: Horizontal Centering
HTML
<div class="parent">
<div class="child">margin: 0 auto</div>
</div>
<div class="text-center">text-align: center</div> CSS
.parent { width: 100%; background: #f1f5f9; padding: 12px; border-radius: 6px; }
.child { width: 200px; margin: 0 auto; background: #6366f1; color: white; padding: 12px; text-align: center; border-radius: 4px; font-weight: bold; }
.text-center { text-align: center; background: #eef2ff; padding: 12px; border-radius: 6px; margin-top: 8px; font-weight: bold; }
Live Output Window
Vertical Centering
Demo: Vertical Centering
HTML
<div class="flex-center">
<div>Flexbox centering</div>
</div> CSS
.flex-center {
display: flex;
align-items: center;
justify-content: center;
height: 120px;
background: #eef2ff;
border-radius: 8px;
font-weight: bold;
color: #6366f1;
font-size: 1.125rem;
}
Live Output Window
Grid Centering
Demo: Grid Centering
HTML
<div class="grid-center">
<div>Grid place-items: center</div>
</div> CSS
.grid-center {
display: grid;
place-items: center;
height: 120px;
background: #ecfdf5;
border-radius: 8px;
font-weight: bold;
color: #059669;
font-size: 1.125rem;
}
Live Output Window
Complete Centering Methods
| Method | Horizontal | Vertical | Use Case |
|---|---|---|---|
margin: 0 auto |
Yes | No | Block elements with width |
text-align: center |
Yes | No | Inline/inline-block content |
line-height: height |
No | Yes | Single line text |
| Flexbox | Yes | Yes | Most flexible approach |
Grid + place-items |
Yes | Yes | Simplest for grid containers |
position: absolute + transform |
Yes | Yes | Overlay/modal centering |
For most cases, Flexbox is the most reliable centering solution.
Keep learning
Related tutorials from across the library.
Tutorial
Introduction to CSS
Learn what CSS is and why it matters
Web Development / Frontend / CSS
CSSWeb Development
Tutorial
History of CSS
Understand how CSS evolved
Web Development / Frontend / CSS
CSSWeb Development
Tutorial
Adding CSS
Three ways to add CSS to a page
Web Development / Frontend / CSS
CSSWeb Development