Vertical Align an element in CSS
Dear experts, I was trying to align an paragraph to the middle of an division element via CSS and I somehow c开发者_JS百科an't get it to work.
<style type="text/css">
.wrap{
background:red;
height: 5em;
}
p{
background:blue;
height: 2em;
vertical-align:middle;
}
</style>
<div class="wrap">
<p>
ALIGN TEXT
</p>
</div>
It doesn't work in IE nor firefox,
Here's a nice hackish example, i'd put the IE css in conditionals instead of hiding it with hacks, other that that nice.
<div style="display: table; height: 400px; #position: relative; overflow: hidden;">
<div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
<div class="greenBorder" style=" #position: relative; #top: -50%">
any text<br>
any height<br>
any content, for example generated from DB<br>
everything is vertically centered
</div>
</div>
</div>
http://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align
"Applies to: inline-level and 'table-cell' elements"
http://phrogz.net/CSS/vertical-align/
Alternatively you can use vertical-align:middle
, display:inline-block
, and an empty inline element with 100% height:
http://jsfiddle.net/HVtuD/
<div id='container'>
<div id='text'>vertical-align + inline-block<br>trick<br>in action</div>
</div>
#container{
height: 300px;border: 1px solid black;text-align:center;
}
#text,#container:before{
vertical-align: middle;
display: inline-block;
}
#container:before{
content: "";
height: 100%;
width: 0%;
}
It's impossible to vertically align anything without it being a table, or without using Javascript.
精彩评论