What is the easiest method for vertical+horizontal centering of a div in the window?
Given a div
with known dimensions, say width: 300px; height: 200px
, what is the easiest method to place it in the middle of the screen both vertically and horizontally ? Example here
I'm开发者_如何学Go interested in latest Firefox (no need for IE hacks).
CSS only please, no Javascript.
Position it 50% from the window/parent container and use a negative margin size that's half of the elements width/height :)
position: absolute; // or fixed if you don't want it scrolling with the page.
width: 300px;
height: 200px;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -100px;
You might need to set height: 100%
, on both the body
and html
html, body {
height: 100%;
}
Edit: Here's a working example .
Without supporting IE, this is actually pretty easy to achieve using display: table
and display: table-cell
.
Here's an update to your HTML:
<div id='my_div'>
<div class="centered">this is vertically centered</div>
</div>
CSS:
body, html
{
height: 100%;
}
body
{
margin: 0;
padding: 0;
border: 1px solid blue;
}
#my_div
{
width: 300px;
border: 1px solid red;
margin-left: auto;
margin-right: auto;
height: 100%;
display: table;
overflow: hidden;
}
.centered
{
display: table-cell;
vertical-align: middle;
text-align: center;
}
And to preview: http://jsfiddle.net/we8BE/
I don't know if this is the simplest way, but it seems to work.
http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm
What methods are you open to using? For example CSS up to what level - 2 or 3? Javascript? jQuery? My first thought is that, since divs can be centred horizontally through margin-left: auto;
and margin-right: auto;
, maybe try margin: auto;
for all 4 sides. Let me know if it works.
The easiest? One of the numerous jQuery center plugins available...
精彩评论