Vertically centering a div in a parent div
This is simpler than before. The parent-div needs to have display: table-cell; vertical-align: middle; and the child-div needs to have display: inline-block;.
In the case where I want to center something in div-table, the class .cell will already have display: table-cell; so I only need to add vertical-align: middle; to .cell and then forgo class .outer.
.outer {
display: table-cell;
vertical-align: middle;
}
.inner {
display: inline-block;
}
<div class='outer'>
<div class='inner'>
</div>
</div>
<div class='box' style='height: 200px; border: 2px solid #fc7e;'> <!-- this needs a height -->
<div style='display: table; height: 100%; width: 100%;'>
<div style='display: table-cell; vertical-align: middle;'>
<div style='height: 30px; background-color: #eee;'></div>
</div>
</div>
</div>
In this case, the .box has a height height: 200px, and we want to vertically center a div inside of it.
Its first child div can be display: table; height: 100%;
The inner div doesn't need anything really, that's just to center the text.
horizontally
this works amazingly!
.outer {
display: table;
height: 100%;
width: 100%;
}
.inner {
display: table-cell;
vertical-align: middle;
}
#main {
display: table;
margin: 0 auto;
}
if you want to center horizontally, there is sthing to think of
- is it text? if so, then use text-align: center;
- is it a box with known size? is it a block element? then use margin: 0 auto;
Ie. if you have sthing like the following, it won't work, because .inner has width=auto
<style>
.inner {
margin: 0 auto;
border: 1px solid #999;
}
</style>
<div class='outer'>
<div class='inner'>
<p> words </p>
</div>
</div>