Partager via


About Element Positioning

Windows Internet Explorer supports the ability to position HTML elements in x- and y-coordinates and to overlap elements in planes along the z-axis, which extends toward and away from the viewer in a Web document. These capabilities allow authors to precisely place elements, images, controls, or text on to a web page. By using scripts to manipulate the position coordinates and other dynamic styles, authors can move elements around a page, creating animated effects. The combination of dynamic styles, positioning, transparent Microsoft ActiveX Controls, and transparent images presents authors with a rich set of animation options.

  • What Is Positioning?
  • Absolute Positioning
  • Fixed Positioning
  • Relative Positioning
  • Positioning Considerations
    • Combining Dynamic Positioning Techniques
  • Controlling Content Visibility
    • Clipping Regions and Overflow
    • Z-Index Ordering
  • Element Visibility

What Is Positioning?

Cascading Style Sheets (CSS) Positioning defines the placement of elements on a page and is an extension of cascading style sheets as specified in the W3C Working Draft on Positioning HTML with CSS. By default, elements flow one after another in the same order as they appear in the HTML source, with each element having a size and position that depends on the type of element, the contents of the element, and the display context for the element as it will render on the page. This default flow model for HTML layout doesn't allow a high level of control over the placement of elements on the page. By applying a small set of CSS attributes to the elements that are defined for the page, CSS can control the precise position of elements by giving exact coordinates. It is also possible to specify placement relative to the position of other objects on the page.

Just like any other HTML or CSS attribute, the CSS attributes used to control an element's position are available for scripting. The position of these elements on the page can thus be dynamically changed with script. As a result, the position of these elements can be recalculated and redrawn after the document is loaded without reloading the page from the server.

Controlling an elements position can make use of a variety of layout techniques. By employing specific parameters the site designer is in complete control over how much of an element is displayed on a page (if at all).

There are three ways to position an element in x- and y-coordinates. The type of positioning to use depends on the layout of the content and the purpose of the document. Absolute positioning means that the element is precisely placed relative to the parent coordinate system, regardless of any other content. Fixed positioning gives elements precise placement relative to the browser window, outside the flow of other content. Relative positioning places the item with respect to other elements on the page. Relative positioning depends on the default flow of the document, and reflows content should the user resize the browser.

In most cases, we recommend that websites use the HTML5 document type to support the widest variety of established and emerging standards, as well as the broadest range of web browsers. This example shows how to specify the HTML5 document type.

<!DOCTYPE html>

Note  Fixed positioning is available through strict mode in Windows Internet Explorer 7 and Windows Internet Explorer 8. For more info, see "Specifying legacy document modes"

Absolute Positioning

An absolutely positioned element is always relative to the next positioned parent. If there isn't a parent element, the containment block is used instead. Values for left and top are relative to the upper-left corner of the next positioned element in the hierarchy. For example, to place an image at the top left corner of the document, set the attributes to 0.

<img src="sample.gif" style="position:absolute; left:0px; top:0px">

This positions the image within the border of the HTML element. Be aware that the HTML element has a default border of 1, If you do not want two borders, set the border of the body to 0 to position the image at the 0,0 coordinates of the client area.

To see how a positioned parent affects the absolute position, consider the following example.

<div style="position:relative;left:50px;top:30px;height:100px;width:100px">
    Some text inside the DIV that will be hidden by the image because the image
    will be positioned over this flowing text.
<img src="sample.gif" style="position:absolute; left:0px; top:0px">
<div>

This example places the img element at the upper-left corner of the div element, which is itself positioned on the page.

Setting an absolute position pulls the element out of the flow of the document and positions it without regard to the layout of surrounding elements. If other elements already occupy the given position, they do not affect the positioned element, nor does the positioned element affect them. Instead, all elements are drawn at the same place, causing the objects to overlap. You can control this overlap by using the z-index attribute to specify the order in which elements are stacked at the same location.

The contents of a positioned element flow within the given dimensions as default HTML would flow. For instance, text wraps normally based on the width of the element, and various inline elements contained within the positioned elements are placed next to each other in source order according to the constraints of size and shape of the container (that is, the positioned element).

Fixed Positioning

Beginning in Internet Explorer 7, web developers can use fixed positioning, a subcategory of absolute positioning. Similar to the containing boxes of absolute positioning, fixed position elements are independent. When applied, they are not relative to preexisting parent or child elements. The distinction involves element placement. Rather than localization on the body of a page (as with absolute positioning), the contents of a fixed positioned element flow within the given dimensions of the browser window (also known as the viewport).

The following example includes a typical layout representing fixed attributes.

<!DOCTYPE html>
 <html><head><title>Fixed Positioning Example</title><style type="text/css">     
    body{height=640px; width=480px;} 
      #logoBar  {position:fixed;width:99.15%;height:15%;top:0;right:0;bottom:auto;left:0;border:solid;}
      #leftSide {position:fixed;width:10em;height:auto;top:15%;right:auto;bottom:50px;left:0;border:solid}
      #main     {position:fixed;width:auto;height:auto;top:15%;right:0;bottom:50px;left:10em;border:solid}
      #footer   {position:fixed;width:99.15%;height:50px;top:auto;right:0;bottom:0;left:0;border:solid;} 
    </style></head><body>
    <div id="logoBar">...logobar...</div>
    <div id="leftSide">...leftside...</div>
    <div id="main">...main...</div>
    <div id="footer">...footer...</div> 
    </body></html>

Click to view sample.

In this example, the fixed containers are out of the flow of the page contents. Their positions remain relative to the viewport even as the browser window is resized. Once defined, they do not move from their assigned locations; making it possible for them to block elements beneath them. This makes careful placement a necessary consideration in your page design.

Relative Positioning

Setting the CSS position attribute to "relative" places the element in the natural HTML flow of the document and offsets the position of the element based on the preceding content. For example, placing a piece of text within a paragraph with "relative" positioning renders the text relative to the text in the paragraph that precedes it.

<p>The superscript in this name<span style="position: relative; top:-3px">xyz</span> is "xyz".</p>

Should the user resize the window, the "xyz" still appears three pixels above the natural baseline of the text. You can set the left attribute in a similar way to change the horizontal spacing between "name" and "xyz". If the contents of the span were absolutely positioned, the "xyz" would be placed relative to the HTML element (or the next positioned element in the hierarchy), and the "xyz" would be barely visible at the upper corner of the client area - probably not the effect the author intended!

Text and elements that follow a relatively positioned element occupy their own space and do not overlap the natural space for the positioned element. Contrast this with an absolutely positioned element where subsequent text and elements occupy what would have been the natural space for the positioned element before the positioned element was pulled out of the flow.

It is quite possible that relatively positioned elements will overlap with other objects and elements on the page. As with absolute positioning, you can use the z-index attribute to set the z-index of the positioned element relative to other elements that might occupy the same area. By default, a positioned element always has a higher z-coordinate than its parent element so that it will always be on top of its parent element.

Positioning Considerations

The type of positioning to use depends on the layout of the content and the purpose of the document. Relative positioning depends on the default flow of the document and reflows content when the user resizes the browser. Fixed positioning, with its direct relation to the browser window also responds by reflowing when the window is resized. However, absolute positioning precisely places images and text no matter what the user does to the display.

Here is an example 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 use tables and attributes to center the content inside a table cell. However, this layout restricts you to a static table. Using positioning, this content can be worked into a larger layout, and then you can add scripting that might, for instance, have each of these elements fall into place from somewhere outside the document as the user loads the page!

<!DOCTYPE html>
<html>

<head>
  <title>Center the DIV</title>
</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 &lt;div&gt; element.
    <div id="two" style="position: absolute; left: 50px; width: 100px; color: red; border: red 2px solid">
      Text in the inner &lt;div&gt; element - color is red.
    </div>
    <div style="width: 100px; margin: auto; border: 1px solid blue; color: blue;">Centered via CSS - color is blue.</div>    
  </div>
  <script>
    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>  
</body>

</html>

Click to view sample.

In the example above, the outer div flows with the contents of the document that precedes it, meaning it is positioned 10 pixels immediately after the first paragraph. The inner div has an initial absolute position, but this position is modified by the script function "doPosition" when the document is loaded. The offsetWidth and offsetHeight properties are used to calculate the new absolute position for an element. The example can also use the posLeft or pixelLeft property to center the images. These properties give alternate access to the left property, letting you set the position using a floating point number or an integer. There are similar properties that provide alternate access to the top, width, and height properties.

Combining Dynamic Positioning Techniques

The previous example can be expanded to manipulate multiple items on the page. If you were to animate this script, you might rework the scripting function on the documents onload event to have the inner piece of text "fly in" from offscreen. This function could be based on a timer that would move the inner div from an initial top and left coordinate somewhere off the visible portion of the page, and, over a given amount of time, move it to a position that would be in the center of the outer div.

The following example makes the div element visible and animates the content to glide across the screen. By setting an interval using the setInterval method on the window object, you can move one or more elements each time the interval elapses.

<!DOCTYPE html>
<html>

<head>
  <title>Glide the DIV</title>
  <script>
    var action;

    function StartGlide() {
      Banner.style.pixelLeft = document.body.offsetWidth;
      Banner.style.visibility = "visible";
      action = window.setInterval("Glide()",50);
    }

    function Glide() {
      Banner.style.pixelLeft -= 10;
      if (Banner.style.pixelLeft<=0) {
        Banner.style.pixelLeft=0;
        window.clearInterval(action);
      }
    }
  </script>
</head>
<body onload="StartGlide()">
  <p>With dynamic positioning, you can move objects and their content 
    anywhere in the document even after the document has loaded!</p>

  <div id="Banner" style="visibility: hidden; position: absolute; top: 0px; left: 0px">Welcome to Dynamic HTML!</div>
</body>

</html>

Click to view sample.

Note  Dynamically changing an element from nonpositioned to positioned is only supported in Microsoft Internet Explorer 5 or later.

For more ideas on how to integrate positioning with other Dynamic HTML (DHTML) techniques, see Introduction to Filters and Transitions to learn how to incorporate visual filter effects.

Controlling Content Visibility

  • Clipping Regions and Overflow
  • Z-Index Ordering

In addition to controlling where on the page the element is positioned, the content of positioned elements can be restricted from the user's view in several ways. The display and visibility attributes control whether the element appears on the screen at all, and the clip and overflow attributes control how much of the content the user can see. Authors can also control the visibility of overlapping elements by manipulating the z-index ordering.

Clipping Regions and Overflow

You can set a clipping region for a positioned element by using the clip attribute. The clipping region defines a rectangle within which the element is visible. Any portion of the element that extends outside the clipping region is clipped, that is, not displayed. The clipping region does not alter the HTML, but simply changes how the element is displayed.

For example, the following document uses clip to define a clipping region for the absolutely positioned img. The region, a 50-by-50 pixel square, displays only a portion of the image; the rest is clipped from view.

<!DOCTYPE html>
<html>
<head>
<title>Clipping an Image with clip</title>
<meta http-equiv="X-UA-Compatible" content="IE=8" />
<style type="text/css">
img {
    clip: rect(0px,50px,50px,0px);
    position: absolute;
    top: 50px;
}
</style>
</head>

<body>

<h2>Clipping an Image with clip</h2>
<img alt="ielogo" src="ie8_logo.jpg">

</body>

</html>

Click to view sample.

Be careful when you define a clipping region - the parameter order (top, right, bottom, left) is important. For example, setting clip:rect to (0, 0, 50, 50) causes the region not to display because the top and right have been defined as zero. The correct definition for a 50-by-50 clipping region based off the top left corner of the positioned object is to set clip:rect to (0, 50, 50, 0).

You can change the clipping region dynamically by using the clip property, as in the following example.

document.all.MyDiv.style.clip = "rect(0, 50, 75, 0)";

Overflow occurs when there is more content in a positioned element than can fit within the area defined for it. By default, any extra content is displayed but flows beyond the end of the area and therefore may overlap other elements in the document. You can prevent this overflow by using the overflow attribute to either hide the overflow or enable scroll bars to let the user view it by scrolling.

For example, the following document uses the overflow attribute to apply scroll bars. Only the portion of the text that fits within the 100-by-100 area is initially displayed, but the user can scroll the rest into view by using the scroll bars.

<!DOCTYPE html>
<html>
<head><title>Scroll the Overflow</title>
</head>
<body>
<div style="position:absolute;top:50px;left:50px;height:100px;width:100px;
overflow:scroll">
some content some content some content some content some content
some content some content some content some content some content
some content some content some content some content some content
some content some content 
</div>
</body>
</html>

Click to view sample.

You can hide any overflow by setting the overflow attribute to hidden. Similarly, you can let the overflow flow beyond the end of the area by setting it to visible.

You can change the overflow dynamically by using the overflow property, as in the following example:

if (document.all.MyDiv.style.overflow != "scroll")
    document.all.MyDiv.style.overflow = "scroll";

Z-Index Ordering

The z-index specifies in what order elements should be drawn when two or more elements occupy the same area. Setting the z-index is useful whenever you have absolutely or relatively positioned elements that overlap other elements in the document.

You set the z-index by using the z-index attribute. Setting this to a positive value causes the element to be stacked on top of other elements; negative values cause it to be stacked below. The following document uses z-index to stack text on top of the image.

<!DOCTYPE html>
<html>
<head><title>Stack the Image</title>
</head>
<body>
<p style="position:absolute;top:0px;left:0px">Text Over Image</p>
<img src="sample.jpg" style="position:absolute;top:0px;left:0px;z-index:-1"/>
</body>
</html>

Click to view sample.

The element with the greatest z-index is always placed at the very top of the stack, and the element with the least z-index at the very bottom. If two elements have the same z-index, their source order determines the stacking (the last element is stacked highest).

Note  Input from pointing devices, such as the mouse, does not penetrate through overlapping elements even if the elements are not visible. This is also true for positioned elements with a negative z-index unless the parent is a scrolling container (that is, its overflow property is set to auto or scroll), or the parent is manually positioned (that is, its position property is set to absolute, relative, or fixed).

You can change the z-index dynamically by setting the zIndex property, as in the following example.

MyImg.style.zIndex = 2;

In general, all elements are windowless and will participate in z-order overlapping. However, some objects are windowed. ActiveX Controls that have not been specifically written to be windowless will not overlap with other objects. iframe elements represent a window object, and window objects do not participate in z-order. Another exception is the select element which is also a windowed object in Microsoft Internet Explorer 6 and lower. As of Internet Explorer 7, the select element is windowless and supports the z-index attribute and the zIndex property.

Note  Although they are associated with different parts of the rendered page, fixed positioned elements are also subject to the relative stacking order of absolute positioned objects.

Element Visibility

The visibility of a positioned element determines whether the user can see the element. Visibility is useful for temporarily hiding an element, such as when time is needed to calculate its position or when carrying out simple transition effects. You can set the visibility by using the visibility attribute. The following example uses the attribute to make the div element invisible.

<p>A paragraph above the DIV element</p> 
<div id=MyDiv style="position:absolute;top:50px;left:50px;height:100px;
    width:100px;visibility:hidden"></div>
<p>A paragraph below the DIV element</p>

You can set the visibility of an element from script by using the visibility property. For example, assume that the div in the previous example is loaded. Initially, it is invisible, but you can change this to visible by using the following:

MyDiv.style.visibility = "visible";

An element that is not visible continues to affect the document layout; that is, the space that the element would occupy remains in the document even though it is empty. This is unlike the display attribute, which does not reserve space. The following sample demonstrates the difference between visibility and display.

Click to view sample.