How to Center Horizontally in CSS: Simple Methods Explained
To center an element horizontally in CSS, you can use
margin: auto on block elements, text-align: center for inline content, or use Flexbox with display: flex and justify-content: center. These methods work for different types of elements and layouts.Syntax
Here are common CSS patterns to center horizontally:
margin: auto;- centers block elements with a fixed width inside a container.text-align: center;- centers inline or inline-block content inside a block container.display: flex; justify-content: center;- centers any child elements horizontally inside a flex container.
css
/* Center block element with fixed width */ div { width: 200px; margin: 0 auto; } /* Center inline content */ .container { text-align: center; } /* Center with Flexbox */ .container { display: flex; justify-content: center; }
Example
This example shows a blue box centered horizontally 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"> <title>Center Horizontally Example</title> <style> .container { display: flex; justify-content: center; background-color: #ddd; height: 150px; align-items: center; } .box { width: 100px; height: 100px; background-color: #007BFF; } </style> </head> <body> <div class="container"> <div class="box"></div> </div> </body> </html>
Output
A gray horizontal rectangle with a smaller bright blue square perfectly centered horizontally inside it.
Common Pitfalls
Common mistakes when centering horizontally include:
- Using
margin: autowithout setting a fixed width on block elements, which prevents centering. - Trying to center block elements with
text-align: center, which only works for inline content. - Not setting
display: flexon the container before usingjustify-content: center.
css
/* Wrong: margin auto without width */ div { margin: 0 auto; /* missing width, so no centering */ } /* Right: margin auto with width */ div { width: 200px; margin: 0 auto; } /* Wrong: text-align on block element */ div { text-align: center; width: 200px; /* text-align does not center block elements */ } /* Right: text-align centers inline content inside container */ .container { text-align: center; }
Quick Reference
Summary of horizontal centering methods:
| Method | Use Case | Key CSS |
|---|---|---|
| Margin Auto | Block elements with fixed width | width + margin: 0 auto |
| Text Align | Inline or inline-block content | text-align: center on container |
| Flexbox | Any child elements | display: flex; justify-content: center |
Key Takeaways
Use margin: auto with a fixed width to center block elements horizontally.
Use text-align: center to center inline content inside a container.
Use Flexbox with justify-content: center for flexible horizontal centering.
Always set display: flex on the container before using justify-content.
Check element type and layout to choose the right centering method.