问题
How on earth do you center a div vertically?
Horizontal has enough ways already, but no matter what i try, vertical centering is just impossible.
body { vertical-align: middle;}
Does nothing
body {text-align: middle;}
Does nothing
div.middle {top: 50%;}
Does nothing
Is it even possible?
I think i'm gonna cry.
回答1:
See Vertical Centering in CSS.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"> <html> <head> <title>Universal vertical center with CSS</title> <style> .greenBorder {border: 1px solid green;} /* just borders to ser it */ </style> </head> <body> <div class="greenBorder" 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> </body> </html>
回答2:
use Flexible Box Layout Module for doing that. Here is the link to the codepen. This is simple and best solution what i feel. If you are not taking care of the IE Browsers then this is the best method of aligning the Blocks. "Angular Material" is also using this to make its grid.
<div class="center">
<div>
<h4>
I am at center
</h4>
</div>
</div>
.center {
/*this is for styling */
height: 100px;
margin: 1em;
color:#fff;
background: #9f5bd0;
/*you just have to use this */
display: flex;
justify-content:center;
align-items:center;
}
To learn 'Flexible Box Layout Module' you can visit FLEXBOX FROGGY.
回答3:
The div has to have a fixed height in order to make it possible, as far as I know.
#centered { width: 700px; height: 400px; position: absolute; top: 50%; left: 50%; margin: -200px 0 0 -350px; }
And make the parent layer of #centered
relatively positioned. That should work.
Edit - So it is possible to have an undefined height. See cletus' answer.
回答4:
This might Help: http://ask.amoeba.co.in/
回答5:
- Make sure your outer div is "position: relative" OR "position: absolute" (for a point of reference). 2. Set a fixed height for the inner div. 3. Set the inner div to "top: 50%" to move it down to the middle. 4. And the step people forget is to set "margin-top: -yy" (-yy is half the height of the inner div to offset the div upwards).
Say your inner div was set to height: 100px;. The code would be:
<style type="text/css">
#outerDiv { position: relative }
#innerDiv { position: absolute; top: 50%; height: 100px; margin-top: -50px }
</style>
来源:https://stackoverflow.com/questions/1896229/vertical-align-a-block