What is the easiest way to vertically + horizontally center a div in a window?

Given a div with known sizes, say width: 300px; height: 200px width: 300px; height: 200px , what is the easiest way to place it in the middle of the screen both vertically and horizontally? Example here

I am interested in the latest Firefox (no need for IE hacks).

CSS only, no Javascript.

+7
html css alignment vertical-alignment
source share
5 answers

Put it at 50% of the window / parent container and use a negative margin size equal to half the width / height of the elements :)

 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 may need to set height: 100% , both on body and html

 html, body { height: 100%; } 

Edit: It works here.

+9
source share

Without IE support, this is pretty easy to achieve with display: table and display: table-cell .

Here is 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 for preview: http://jsfiddle.net/we8BE/

+1
source share

I don't know if this is the easiest way, but it seems to work.

http://www.infinitywebdesign.com/research/cssverticalcentereddiv.htm

+1
source share

What methods do you use to use? For example, CSS to which level - 2 or 3? Javascript Jquery My first thought is that since divs can be centered horizontally through margin-left: auto; and margin-right: auto; maybe try margin: auto; for all four sides. Let me know if this works.

0
source share

Simplest? One of the many jQuery center plugins available ...

0
source share

All Articles