...

View Full Version : Why does this DIV stay in place?



Alex Vincent
03-19-2008, 01:54 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>A DIV that doesn't scroll</title>
<style type="text/css">
#lightBoxOverlay {
display: block;
position: absolute;
top: 0pt;
left: 0pt;
width: 100&#37;;
z-index: 5000;
height: 2052px;
}

#lightBoxOverlay2 {
display: block;
position: absolute;
top: 0pt;
left: 0pt;
width: 100%;
height: 2052px;
}

#lightBoxMessageWrapper {
width: 100%;
position: fixed;
top: 50%;
}

#offerFormsArea {
display: block;
height: 560px;
width: 684px;
z-index: 5001;
margin: auto;
margin-top: -280px;
border: 2px solid red;
}

#contentblock {
width: 2000px;
height: 2000px;
}
</style>
</head>
<body>
<div id="lightBoxOverlay2"></div>
<div id="lightBoxOverlay">
<div id="lightBoxMessageWrapper">
<div id="offerFormsArea">
<p>This box doesn't appear to move as the user scrolls.</p>
</div>
</div>
</div>
<div id="contentblock">
<div>
<p style="width: 60px;">This content moves as the page scrolls.</p>
</div>
</div>
</body>
</html>


I've been beating my head on this pretty much the whole day. When the window scrolls, the red box doesn't scroll with the rest of the content. What I can't figure out is, why?

This is a reduced testcase from a webpage that I'm trying to fix for my company's product. If I can understand the why, then I can modify the page with a GreaseMonkey-like script to make it work with us.

VIPStephan
03-19-2008, 02:39 AM
Uhm, pretty simple:


#lightBoxMessageWrapper {
width: 100%;
position: fixed;
top: 50%;
}


This positions an element relative to the viewport and forces it to stay there whatever else may happen.

Alex Vincent
03-19-2008, 08:02 PM
Okay, and position: absolute; means it stays in a calculated place on the page.

Thanks! I always forget that difference...

VIPStephan
03-19-2008, 08:11 PM
position: fixed positions an element relative to the viewport, position: absolute positions an element relative to the next positioned (relative, absolute, fixed) ancestor element. This is an important difference. Only if no ancestor is positioned, the absolute position is calculated relative to the html element (most of the times corresponding to the viewport).

Effectively this difference also means that absolutely positioned elements scroll with their ancestors (if they allow for scrolling) while fixed positioned elements are fixed within the viewport, wherever you position them, and scrolling won’t have any effect.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum