How to center horizontally div inside parent div

HtmlCss

Html Problem Overview


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>

Html Solutions


Solution 1 - Html

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;
}

Solution 2 - Html

<div id='parent' style='width: 100%;text-align:center;'>
 <div id='child' style='width:50px; height:100px;margin:0px auto;'>Text</div>
</div>

Solution 3 - Html

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>   

Solution 4 - Html

.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;
}

.child-canvas {
  flex-shrink: 0;
}

Solution 5 - Html

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>

Solution 6 - Html

<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEagleView Question on Stackoverflow
Solution 1 - HtmlMark EmblingView Answer on Stackoverflow
Solution 2 - HtmlJames GoodwinView Answer on Stackoverflow
Solution 3 - HtmlPaul Chris JonesView Answer on Stackoverflow
Solution 4 - HtmlGrigor NazaryanView Answer on Stackoverflow
Solution 5 - Htmlx4uView Answer on Stackoverflow
Solution 6 - HtmlSoufiane HassouView Answer on Stackoverflow