135

How do I center a div horizontally inside its parent div with CSS?

<div id='parent' style='width: 100%;'>
 <div id='child' style='width: 50px; height: 100px;'>Text</div>
</div>
Eagle
  • 1,475
  • 3
  • 11
  • 9
  • 1
    Here are two simple methods to center divs within divs, vertically, horizontally or both (pure CSS): http://stackoverflow.com/a/31977476/3597276 – Michael Benjamin Aug 20 '15 at 14:40

6 Answers6

194

I am assuming the parent div has no width or a wide width, and the child div has a smaller width. The following will set the margin for the top and bottom to zero, and the sides to automatically fit. This centers the div.

div#child {
    margin: 0 auto;
}
Mark Embling
  • 12,605
  • 8
  • 39
  • 53
  • @Mark. Do you know how to make it work in IE6? IE6 really sucks a lot, but still there are some people using it. – Bakhtiyor Sep 07 '11 at 16:02
  • @Bakhtiyor: as far as I remember, it does. What issues are you seeing? you might want to pop open a new question if there's some specific issue you're having which hasn't been touched on before. I don't have access to IE6 to check with though. – Mark Embling Sep 07 '11 at 16:12
  • 3
    @Bakhtiyor: actually having thought about it, I think in IE.old you also need to set `text-align: center;` on the `parent` div and then set it back to left (or whatever) for the `child` one. Not sure if that issue afflicts IE6... – Mark Embling Sep 07 '11 at 16:17
  • @Mark & @Bakhtiyor for some reason i was having my `child` div seemingly shifted to the left--in comparison to browsers that are more standards compliant--in all versions of IE that i checked (IE6-8). And `text-align: center;` for the `parent` and `text-align: left;` for the `child` fixed it for all those versions. – brookmarker Feb 02 '12 at 16:33
12
<div id='parent' style='width: 100%;text-align:center;'>
 <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>
James Goodwin
  • 7,360
  • 5
  • 29
  • 41
11
.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child-canvas {
  flex-shrink: 0;
}
Grigor Nazaryan
  • 567
  • 5
  • 18
7

Just out of interest, if you want to center two or more divs (so they're side by side in the center), then here's how to do it:

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>   
Paul Chris Jones
  • 2,646
  • 1
  • 23
  • 21
4

You can use the "auto" value for the left and right margins to let the browser distribute the available space equally at both sides of the inner div:

<div id='parent' style='width: 100%;'>
   <div id='child' style='width: 50px; height: 100px; margin-left: auto; margin-right: auto'>Text</div>
</div>
x4u
  • 13,877
  • 6
  • 48
  • 58
2
<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>
Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75