How can I horizontally center a <div> within another <div> using CSS?
To horizontally center a <div>
(child) within another <div>
(parent), you have several CSS options. Below are four common approaches:
1. Using margin: 0 auto;
(for block-level elements with a fixed width)
.parent { width: 500px; /* or auto, depending on layout */ background: #ddd; } .child { width: 300px; /* required for margin: auto to work reliably */ margin: 0 auto; /* horizontally center the child */ background: #bbb; }
- How it works:
margin: 0 auto
will automatically calculate the left and right margins to center the child as long as it is a block-level element with a set width.
2. Using text-align: center;
(for inline-block or inline elements)
.parent { text-align: center; background: #ddd; } .child { display: inline-block; /* make it an inline-level element */ background: #bbb; }
- How it works: By setting the parent’s
text-align: center
, any inline or inline-block child is centered horizontally. You do not need a fixed width for the child in this case.
3. Using Flexbox
.parent { display: flex; justify-content: center; background: #ddd; } .child { background: #bbb; /* The child can be any display, flex doesn't require a fixed width. */ }
- How it works: Flexbox will align items along the main axis (horizontal by default). The
justify-content: center;
property centers the child horizontally.
4. Using CSS Grid
.parent { display: grid; justify-content: center; background: #ddd; } .child { background: #bbb; }
- How it works: With CSS Grid,
justify-content: center;
on the parent centers grid items horizontally. Similar to Flexbox, no fixed width is required unless you want to strictly control the child’s size.
Which Method Should You Use?
margin: 0 auto;
is classic for block elements with a known width.text-align: center;
works well for inline/inline-block elements.- Flexbox and CSS Grid are modern, powerful layouts, perfect if you’re already using them for other layout tasks.
Choose the approach that best fits your overall layout strategy and the nature of your <div>
elements.
CONTRIBUTOR
TechGrind