How to center align a div inside a div

Published on Author Code Father
How to center align a div inside a div? How to do a div inside div align center? Horizontally center a div in a divCenter align div inside div? align center a div. Center align divs inside parent div. How can I horizontally center a div within a div using CSS?How to make a div center align in HTML?

You can apply this CSS to the inner div:

#inner {
    width: 50%;
    margin: 0 auto; 
}

Of course, you don’t have to set the width to 50%. Any width less than the containing div will work. The margin: 0 auto is what does the actual centering. If you are targeting IE8+, it might be better to have this instead:

#inner {
    display: table;
    margin: 0 auto;
}

It will make the inner element center horizontally and it works without setting a specific width. Working example here:

#inner {
    display: table;
    margin: 0 auto; 
}
<div id="outer" style="width:100%">  
  <div id="inner">Foo foo</div>
</div>

You can attain this using the CSS Flexbox. You just need to apply 3 properties to the parent element to get everything working.

#outer {
  display: flex;
  align-content: center;
  justify-content: center;
}

Have a look at the code below this will make you understand the properties much better. Get to know more about CSS Flexbox

#outer {
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px solid #ddd;
  width: 100%;
  height: 200px;
 }
<div id="outer">  
  <div id="inner">Foo foo</div>
</div>

 

Comments

comments