What would be the correct method to vertically center any content in a defined width/height div
.
In the example there are two contents with different heights, what is the best way to center vertically both using the class .content
. (and it works for every browser and without the solution of table-cell
)
Have some solutions on mind, but would like to know other ideas, one is using position:absolute; top:0; bottom: 0;
and margin auto
.
I have researched this a little and from what I have found you have four options:
If you do not mind using the display:table-cell
on your parent div, you can use of the following options:
.area{
height: 100px;
width: 100px;
background: red;
margin:10px;
text-align: center;
display:table-cell;
vertical-align:middle;
}
.area{
height: 100px;
width: 100px;
background: red;
margin:10px;
text-align: center;
display:block;
}
.content {
height: 100px;
width: 100px;
display:table-cell;
vertical-align:middle;
}
.area{
background: red;
margin:10px;
text-align: center;
display:block;
float: left;
}
.content {
display:table-cell;
vertical-align:middle;
height: 100px;
width: 100px;
}
The only problem that I have had with this version is that it seems you will have to create the css for every specific implementation. The reason for this is the content div needs to have the set height that your text will fill and the margin-top will be figured off of that. This issue can be seen in the demo. You can get it to work for every scenario manually by changing the height % of your content div and multiplying it by -.5 to get your margin-top value.
.area{
position:relative;
display:block;
height:100px;
width:100px;
border:1px solid black;
background:red;
margin:10px;
}
.content {
position:absolute;
top:50%;
height:50%;
width:100px;
margin-top:-25%;
text-align:center;
}