In this tutorial we will learn how to horizontally center a div
within a div
using CSS.
We are going to use the following html in the whole tutorial:
<div id="outer">
<div id="inner">Foo foo</div>
</div>
Our objective is to horizontally center inner which is inside outer We will use many alternative approaches to solve the issue.
Straigh forward approach
You can use the following css to solve the centering problem:
#inner {
width: 50%;
margin: 0 auto;
}
For width you don't have to set the width to 50%, width less than the containing div will work.
The margin: 0 auto
is what solves our problem of centering the inner div.
For IE8+ you need to add display: table; instead of width in the inner.
Using the box model
#outer{
width:100%; /* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center; /* Safari and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center; /* W3C */
display:box;
box-pack:center;
box-align:center;
}
#inner{
width:50%;
}
According to your usability you may also use the box-orient, box-flex, box- direction
properties.
Using flex
#outer {
display: flex;
flex-direction: row;
flex-wrap: wrap;
justify-content: center;
align-items: center; }
W3C's box model could be counter-intuitive for some people. A box is usually measured from border to border, but with W3C you will measure the content.
Solution avoiding fixed width
To avoid a fixed width in the inner div
, try this css:
#outer {
width: 100%;
text-align: center;
}
#inner {
display: inline-block;
}
That makes the inner div
into an inline element that can be centered with text-align
.
Solution with a fixed width div
If you have a div with 200px
wide:
.centered {
position: absolute;
left: 50%;
margin-left: -100px;
}
The parent element must be positioned with:
- relative
- fixed
- absolute
- sticky
Your final code should be like this:
#outer {
position: relative;
}
#inner {
margin: auto;
position: absolute;
left:0;
right: 0;
top: 0;
bottom: 0;
}
This solution will also work even when the screen is re-sized.