Centre A Div Horizontally And Vertically Regardless Of Window
We’ve already covered how to centre a web page horizontally regardless of screen resolution. Sometimes though, you may want to centre a div horizontally and vertically.
A typical example where I use this technique is for a client log-in page. The page consists of a simple log-in box where the user can enter a username and password to access the admin control panel.
As there is nothing else on this page, I like to have the log-in box smack bang in the middle of the browser. Fortunately, it’s very easy to do:
HTML
1 2 3 4 5 6 7 8 9 10 11 12 | <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <link rel="stylesheet" type="text/css" href="style.css" /> <title>Centre A Div Horizontally And Vertically</title> </head> <body> <div id="login"></div> </body> </html> |
CSS
1 2 3 4 5 6 7 8 9 10 | #login { height:300px; width:300px; position:absolute; top:50%; left:50%; margin-top:-150px; margin-left:-150px; background-color:#000; } |
The CSS is straight forward. We specify a height and width for #login and then position it absolutely 50% from the top and left of the browser.
At first, you might think that this is all we need to do; 50% is half way right? However, this only places the top, left corner of our #login div in the centre of the browser, meaning that the div itself is offset to the right and bottom.
To rectify this, we add negative top and left margins to the div equal to half the div’s height and width respectively. This has the effect of pulling the div in to the centre.
You can see an example here.
Other Posts You Might Like :)


Leave a Comment