Problem
I’d like to place a div> (or a table>) element in the middle of the screen, regardless of screen size. In other words, the space left on the ‘top’ and ‘bottom’ sides should be equal, as should the space left on the ‘right’ and ‘left’ sides. I’d like to achieve this using solely CSS.
I’ve tried the following, but it doesn’t seem to work:
<body>
<div style="top:0px; border:1px solid red;">
<table border="1" align="center">
<tr height="100%">
<td height="100%" width="100%" valign="middle" align="center">
We are launching soon!
</td>
</tr>
</table>
</div>
</body>
Note: Whether or whether the div> element (or table>) scrolls with the website is irrelevant. All I want it to be when the page loads is for it to be centered.
Asked by sumit
Solution #1
If you have a fixed width and height, the easy solution is to:
#divElement{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
}
Please refrain from using inline styles! A functioning example can be found at http://jsfiddle.net/S5bKq/.
Answered by einstein
Solution #2
You can do this now since transformations are more widely supported, even if you don’t know the popup’s width/height.
.popup {
position: fixed;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}
Easy! Here’s a link to JSFiddle: http://jsfiddle.net/LgSZV/
Update: For a fairly comprehensive reference on CSS centering, go to https://css-tricks.com/centering-css-complete-guide/. I’m including it in my answer because it seemed to get a lot of attention.
Answered by XwipeoutX
Solution #3
You’re done once you’ve set the width and height.
div {
position: absolute;
margin: auto;
top: 0;
right: 0;
bottom: 0;
left: 0;
width: 200px;
height: 200px;
}
Choose XwipeoutX’s solution if you want the element dimensions to be flexible (and don’t care about legacy browsers).
Answered by Era
Solution #4
It can be used on any item. Even if you are unsure of the size:
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Answered by luminousmen
Solution #5
With HTML 5 and CSS 3, it’s a lot easier now:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body > div {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
}
</style>
</head>
<body>
<div>
<div>TODO write content</div>
</div>
</body>
</html>
Answered by Daniel De León
Post is based on https://stackoverflow.com/questions/9862167/positioning-div-element-at-center-of-screen