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
.
This question is related to
html
css
vertical-alignment
I found this solution in this article
.parent-element {
-webkit-transform-style: preserve-3d;
-moz-transform-style: preserve-3d;
transform-style: preserve-3d;
}
.element {
position: relative;
top: 50%;
transform: translateY(-50%);
}
It work like a charm if the height of element is not fixed.
I would say to add a paragraph with a period in it and style it like so:
<p class="center">.</p>
<style>
.center {font-size: 0px; margin-bottom: anyPercentage%;}
</style>
You may need to toy around with the percentages to get it right
Simple trick to vertically center the content of the div is to set the line height to the same as height:
<div>this is some line of text!</div>
div {
width: 400px
height: 50px;
line-height: 50px;
}
but this is works only for one line of text!
Best approach is with div as container and a span with the value in it:
.cont {
width: 100px;
height: 30px;
display: table;
}
.val {
display: table-cell;
vertical-align: middle;
}
<div class="cont">
<span class="val">CZECH REPUBLIC, 24532 PRAGUE, Sesame Street 123</span>
</div>
margin: all_four_margin
by providing 50% to all_four_margin will place the element at the center
style="margin: 50%"
you can apply it for following too
margin: top right bottom left
margin: top right&left bottom
margin: top&bottom right&left
by giving appropriate % we get the element wherever we want.
This could also be done using display: flex
with only a few lines of code. Here is an example:
.container {
width: 100px;
height: 100px;
display: flex;
align-items: center;
}
Source: Stackoverflow.com