Export (0) Print
Expand All

Positioning considerations

The type of positioning you choose to apply to an element depends on the layout of the content and the purpose of the page. Relative positioning depends on the default flow of the document and reflows content when the user resizes the browser. Fixed positioning, with its direct relationship to the browser window, also responds by reflowing when the browser window is resized. However, absolute positioning precisely places images and text whether or not the user resizes the browser.

Nesting different positioning types

The following code sample demonstrates the concept of nesting an absolutely positioned element within a relatively positioned element. The desired effect is to center text in a rectangle. In the past, you might have used tables and attributes to center the content inside a table cell. However, this layout restricts you to a static table. By using position attributes, you can work this content into a larger layout, after which you can add scripting that might, for example, animate each of these elements so that they appear to fall into place from somewhere outside the document as the user loads the page.

<html>
<head><title>Center the div</title>
<script language="Jscript">
function doPosition() {
two.style.top = document.all.one.offsetHeight/2 - 
two.offsetHeight/2;
two.style.left = document.all.one.offsetWidth/2 - 
two.offsetWidth/2;
}
</script>
</head><body onload="doPosition()">
<p>Some text in the beginning.</p>
<div id="one" 
    style="position: relative; top: 10px; 
    height: 200px; width: 200px; 
    background-color: green;">Some text in the outer div
    <div id="two" style="position: absolute;
       left: 50px; width: 100px; border :red 2px solid;
       color: red;">text in the inner div - color should be red
    </div>
<div>
</body>
</html>

In this example, the outer DIV element flows with the contents of the page, because it is positioned ten pixels immediately after the first paragraph. The inner DIV element has an initial absolute position, but this position is modified by the doPosition script function when the document is loaded. The offsetWidth and offsetHeight properties are used to calculate the new absolute position for an element.

See also

Send feedback about this topic to Microsoft. © 2011 Microsoft Corporation. All rights reserved.

Community Additions

ADD
Show:
© 2014 Microsoft