How to Center a Div in HTML: Simple Methods Explained
To center a
div horizontally, use margin: auto with a fixed width. For both horizontal and vertical centering, use CSS Flexbox by setting the parent to display: flex and justify-content and align-items to center.Syntax
Here are two common ways to center a div:
- Horizontal center with margin: Set a fixed width on the
divand usemargin-left: autoandmargin-right: auto. - Horizontal and vertical center with Flexbox: Set the parent container to
display: flex, then usejustify-content: centerfor horizontal centering andalign-items: centerfor vertical centering.
css
/* Horizontal center with margin */ div { width: 200px; margin-left: auto; margin-right: auto; } /* Horizontal and vertical center with Flexbox */ .parent { display: flex; justify-content: center; align-items: center; height: 300px; /* needed for vertical centering */ }
Example
This example shows a red box centered both horizontally and vertically inside a gray container using Flexbox.
html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Center Div Example</title> <style> .container { display: flex; justify-content: center; align-items: center; height: 300px; background-color: #ddd; } .box { width: 150px; height: 150px; background-color: #e74c3c; } </style> </head> <body> <div class="container"> <div class="box"></div> </div> </body> </html>
Output
A gray rectangular area 300px tall with a red square box perfectly centered horizontally and vertically inside it.
Common Pitfalls
Some common mistakes when centering a div include:
- Not setting a fixed width when using
margin: auto, so thedivtakes full width and appears not centered. - For vertical centering, forgetting to set a height on the parent container when using Flexbox.
- Using
text-align: centerwhich only centers inline content, not block elements likediv.
css
/* Wrong: margin auto without width */ div { margin-left: auto; margin-right: auto; /* no width set, so div fills container width */ } /* Right: margin auto with fixed width */ div { width: 200px; margin-left: auto; margin-right: auto; }
Quick Reference
- Horizontal center: Use
margin: 0 auto;with fixed width. - Horizontal & vertical center: Use Flexbox on parent:
display: flex; justify-content: center; align-items: center;. - Vertical center needs height: Parent must have a height for vertical centering.
Key Takeaways
Use margin auto with fixed width to center a div horizontally.
Use Flexbox on the parent container to center a div both horizontally and vertically.
Always set a height on the parent when vertically centering with Flexbox.
Avoid using text-align for centering block elements like divs.
Test your layout in the browser to confirm centering works as expected.