Align contents inside a div
You can do it like this also:
HTML
<body>
<div id="wrapper_1">
<div id="container_1"></div>
</div>
</body>
CSS
body { width: 100%; margin: 0; padding: 0; overflow: hidden; }
#wrapper_1 { clear: left; float: left; position: relative; left: 50%; }
#container_1 { display: block; float: left; position: relative; right: 50%; }
As Artem Russakovskii mentioned also, read the original article by Mattew James Taylor for full description.
Below are the methods which have always worked for me
- By using flex layout model:
Set the display of the parent div to display: flex;
and the you can align the child elements inside the div using the justify-content: center;
(to align the items on main axis) and align-items: center;
(to align the items on cross axis).
If you have more than one child element and want to control the way they are arranged (column/rows), then you can also add flex-direction
property.
Working example:
.parent {
align-items: center;
border: 1px solid black;
display: flex;
justify-content: center;
height: 250px;
width: 250px;
}
.child {
border: 1px solid black;
height: 50px;
width: 50px;
}
<div class="parent">
<div class="child"></div>
</div>
2. (older method) Using position, margin properties and fixed size
Working example:
.parent {
border: 1px solid black;
height: 250px;
position: relative;
width: 250px;
}
.child {
border: 1px solid black;
margin: auto;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 50px;
position: absolute;
width: 50px;
}
<div class="parent">
<div class="child"></div>
</div>
text-align aligns text and other inline content. It doesn't align block element children.
To do that, you want to give the element you want aligned a width, with ‘auto’ left and right margins. This is the standards-compliant way that works everywhere except IE5.x.
<div style="width: 50%; margin: 0 auto;">Hello</div>
For this to work in IE6, you need to make sure Standards Mode is on by using a suitable DOCTYPE.
If you really need to support IE5/Quirks Mode, which these days you shouldn't really, it is possible to combine the two different approaches to centering:
<div style="text-align: center">
<div style="width: 50%; margin: 0 auto; text-align: left">Hello</div>
</div>
(Obviously, styles are best put inside a stylesheet, but the inline version is illustrative.)
<div class="content">Hello</div>
.content {
margin-top:auto;
margin-bottom:auto;
text-align:center;
}