...

View Full Version : centering a div in css



tpeck
11-20-2011, 09:44 AM
I have this div:


<div align="center" id='slowScreenSplash' style='position:absolute;z-index:1;top:220px;left:98px'>
<img border="0" id="mainImage1" src="blueani2c.gif" width="1040" height="450">
</div>

The position from the top is perfect - and easily positioned as above.

But how do I change that "left:98px" such that it always centres on the screen?

I know there are centering routines, but how does CSS alter itself accordingly?

coothead
11-20-2011, 10:35 AM
Hi there tpeck,

try it like this...


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta name="language" content="english">
<meta http-equiv="Content-Style-Type" content="text/css">

<title></title>

<style type="text/css">
#slowScreenSplash {
margin-top:220px;
}
#slowScreenSplash img {
display:block;
width:1040px;
height:450px;
margin:auto;
}
</style>

</head>
<body>

<div id="slowScreenSplash">
<img src="blueani2c.gif" alt="">
</div>

</body>
</html>

coothead

Amphiluke
11-20-2011, 10:35 AM
left:50%;
margin-left:-520px;


or (in the general case)


left:50%;
margin-left:-{Width/2}px;

tpeck
11-20-2011, 11:58 AM
Both ways work, but I want to use position:absolute, so I'm using the second.

Thanks!

coothead
11-20-2011, 12:08 PM
Hi there tpeck,

there is one problem with the position:absolute method, of which you may not be aware. ;)
If the page width is reduced there will come a point when the image will start to disappear to the left. :eek:

coothead

Sammy12
11-20-2011, 07:11 PM
I didn't look at the code, but margin: 0 auto; would be the better way

http://www.w3schools.com/css/css_margin.asp

from w3schools:
auto The browser sets the margin.

VIPStephan
11-20-2011, 07:19 PM
I didn't look at the code, but margin: 0 auto; would be the better way

Not with absolute positioning.
tpeck, if you want to center an absolutely positioned element you need to position it 50% left or right and then apply a negative margin of half its width in the opposite direction. This requires the element to have a specific width, though.



element {
width: 200px;
position: absolute;
left: 50%;
margin-left: -100px; /* half the width of the element */
}
/* alternative */
element {
width: 200px;
position: absolute;
right: 50%;
margin-right: -100px;
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum