CSS alignment techniques position text, block containers, and child elements horizontally and vertically within parent boxes.
Different alignment methods apply based on element types:
/* 1. Horizontal Text Alignment */
p { text-align: center; }
/* 2. Block Element Centering */
.container { width: 80%; margin: 0 auto; }
/* 3. Modern Flexbox Centering (Recommended) */
.flex-center {
display: flex;
justify-content: center; /* Horizontal alignment */
align-items: center; /* Vertical alignment */
}
/* 4. Modern Grid Centering */
.grid-center {
display: grid;
place-items: center;
}
Alignment scenarios:
text-align: center.margin: 0 auto with a declared width/max-width.justify-content & align-items) or Grid (place-items: center).flowchart TD
A["Flexbox Container (display: flex)"] --> B["justify-content: center (Main axis alignment)"]
A --> C["align-items: center (Cross axis alignment)"]
B & C --> D["Perfect Center Point Alignment"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Alignment Demonstration</title>
<style>
.hero-center {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 250px;
background-color: #1e293b;
border-radius: 8px;
text-align: center;
padding: 2rem;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<div class="hero-center">
<h2 style="color: #38bdf8; margin: 0;">Perfectly Centered Content</h2>
<p style="color: #94a3b8; max-width: 400px;">Flexbox handles vertical and horizontal alignment effortlessly.</p>
</div>
</body>
</html>
top: 50%; transform: translateY(-50%)).display: grid; place-items: center; for concise 2-line centering: The fastest way to center child elements in CSS.min-height.Create a CSS class .center-box using Flexbox (display: flex; justify-content: center; align-items: center;)!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.