...

View Full Version : Absolute positioning not working?



one_too_many
07-21-2008, 07:02 PM
I am giving a div an absolute position, but it is being offset by the parent div (also absolute) offsets.

I am very confused by this behaviour. It is happening in both Firefox (2+) and IE (6+).

I have a div that I need to use absolute positioning for so I can show a tool tip near the mouse location. I have no problem managing that. My problem is that when I position my div at the absolute location of the mouse, it is being offset by the containing div's offset. I have reduced the problem to this example.

I have a div (id = x) that is set to position: absolute. Top and left are specified as 0px. But, the div appears at the top left corner of its containing div, not the top left of the document where it should be (unless my understading is off).

The containing div has id="main". It must also be positioned with absolute.
This nesting results in my 'x' div being drawn at the wrong location. Full code is below. Can anyone explain this or lead me to a fix? I would be very grafeul!

Thanks!
## Example of absolute div placed w/ offset of parent div ##
<html>
<head>
<title>Absolute Layout Bug?</title>

<style>

#main {
position: absolute;
top: 74px;
left: 185px;
border: 1px solid #0f0;
}

#x {
position: absolute;
top: 0px;
left: 0px;
border: 1px solid #00f;
}


</style>
</head>
<body>
<div id="main">
<h1>What's New</h1>
<div id="x">I should be in the top left corner of the page! Right?!?</div>
</div>
</body>
</html>

_Aerospace_Eng_
07-21-2008, 07:12 PM
Its working properly. It goes by the nearest positioned parent element. Change

#main {
position: absolute;
top: 74px;
left: 185px;
border: 1px solid #0f0;
}
to this

#main {
margin-top: 74px;
margin-left: 185px;
border: 1px solid #0f0;
}

one_too_many
07-21-2008, 07:16 PM
Thanks for the speedy reply. I guess I need to do some more reading! :)

macwiz
07-22-2008, 04:52 AM
I would use percentages instead of pixels for sizing, if you must use absolute positioning. It creates a more fluid layout, and makes the site more consistant across different screen resolutions, as it is a proportion, not a definite number.

If you want to use pixels, look at relative positioning instead.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum