Log in

View Full Version : Positioning a div



d-machine
03-25-2010, 09:50 PM
Hi,

How can I put a div always on the center of the screen? (vertically and horizontally)


Thanks!

djr33
03-25-2010, 09:52 PM
Are you looking for how to center the div, or how to keep it static (not moving) while the rest of the page moves around it (scrolling, etc.), or perhaps both?

d-machine
03-25-2010, 10:04 PM
I'm looking for how to center the div

Thanks :)

molendijk
03-25-2010, 10:29 PM
Example:
<div style="position:absolute; left:50%; top:50%; width: 300px; height:400px; margin-left:-150px; margin-top: -200px; border: 1px solid black"></div>
margin-left is the negative counterpart of width/2; margin-top is the negative counterpart of height/2.
===
Arie Molendijk.

d-machine
03-26-2010, 06:54 AM
Hi, thank you molendijk,
but it doesn't appear on the middle (horizontally yes, but vertically no) of the screen.

My page is long, so you can scroll there, maybe thats the reason.

I want that the div will appear at the center of the screen, wherever I am in the page, without any need for further scrolling.

molendijk
03-26-2010, 10:53 AM
<!--[if IE]>
<style ="text/css">
.center{position:absolute;
top: expression(offsetParent.scrollTop + ((offsetParent.clientHeight-this.clientHeight)/2) +'px' );
left: expression(offsetParent.scrollLeft + ((offsetParent.clientWidth-this.clientWidth)/2) + 'px'); width:200px; height:200px}
body{background: url(foo) fixed}
</style>
<![endif]-->

<!--[if !IE]><!-->
<style type="text/css">
.center{position: fixed; top:50%; left: 50%; width:200px; height:200px; margin-left:-100px; margin-top: -100px}
</style>
<!--<![endif]-->
<div class="center" style="border:1px solid black">centered</div>
===
Arie

simcomedia
03-27-2010, 01:52 AM
1) make sure the div you want displayed in the center has a set width
2) use margin: auto;

molendijk
03-27-2010, 11:32 AM
This is better than what I proposed above, because it does not use IE regular expressions:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
</head>
<body>
<div style="position:fixed; border: 1px solid black; height:80%; top:10%; left:20%;width:60% ">Centered and fixed</div>
</body>
</html>
Works in non-IE and in IE7 and above. For IE, you have to use a valid doctype.
===
Arie.