How to center a div inside another div horizontally?


You have two <div> elements, one <div> inside another <div>. You need to center the texts of the inner <div> in the outer <div> horizontally.


The Code:


<div id="outer">
    <div id="inner">
        Content……………. More content……..hhhhhhhhhalkjdlfkkkkkkkkkklkfjslkjlkd</div>



    margin: 0 auto;
    display: table;


“margin” properties are used to set the white spaces around the elements.

There are four properties of margin. “margin-top”, margin-right”, “margin-bottom” and “margin-left”. If the left-margin and right-margin are equal around an element, it is called the element is centered horizontally.

Margin shorthand property

“margin:0 auto” means

Margin-top: 0px;          [first top]

Margin-right: auto;      [second right]

Margin-bottom: 0px;   [third bottom]

Margin-left: auto;        [fourth left]


The shortcut of those is “margin: 0 auto 0 auto”. As it is repeated “0 auto”. So it can be written “margin: 0 auto”.

When the browser see “auto” property, it calculates available spaces (between outer and inner div spaces) and distributes spaces between margin-left and margin-right equally.

Suppose the width of outer <div> is 80px and the texts of inner <div > take 20px. So there are 60 px available between outer and inner div.  The auto property distributes 60px between margin-left and margin-right equally. So 60/2=30px will be the value of each.

So margin-left: 30px;



Since the left and right and right margins are equal, inner <div> is centered into the outer <div> horizontally.

N.B: IE8+ and other browsers fully support this solution.