CSS Positioning
Contents
Introduction
What is CSS Positioning?
Overview of CSS Positioning Properties
Measuring Element Dimension and Location
1. Positioning Elements (Position Property)
Absolute Positioning (position: absolute)
Relative Positioning (position: relative)
Static Positioning (position: static)
Positioning Considerations
2. Element Visibility (Visibility Property)
3. Clipping Regions (Clip Property)
4. Overflowing Regions (Overflow Property)
5. Z-Index Ordering (Z-Index Property)
Dynamic Positioning
Examples
Table 1. Categories of CSS Properties
Table 2. CSS Positioning Properties
Example #1: Absolutely positioned element with statically positioned parent
Example #2: Absolutely positioned element with relatively positioned parent
Example #3: Absolutely positioned element with absolutely positioned parent
Example #4: Absolutely positioned element with neither top nor left set
Example #5: Absolutely positioned element with top and left set
Example #6: Absolutely positioned element with just top set
Example #7: Absolutely positioned element with just left set
Example #8: Absolutely positioned element with no width or height defined
Example #9: Absolutely positioned element with width defined
Example #10: Absolutely positioned element with relatively positioned child
Example #11: Three same-level relatively positioned elements
Example #12: Three nested relatively positioned elements
Example #13: Three relatively positioned elements; the second is a child of the first
Example #14: Relative, absolute, relative
Example #15: Relative, absolute with relative child, relative
Example #16: Three same-level relatively positioned elements
Example #17: Three nested relatively positioned elements
Example #18:
Example #19:
Example #20:
Example #21:
Example #22:
Example #23: Animate with siblings
Example #24: Animate with children
Example #25:
Introduction
What is CSS Positioning?
Is CSS positioning just another part of CSS, or is it something special? The answer is both. To explain how CSS positioning fits in with CSS in general, let's have a look at the categories of properties found in CSS:
Category |
Description |
Font |
Typography properties |
Color and Background |
Color of text and background, and background image properties |
Text |
Text alignment, spacing, and formatting |
Box |
Box formatting properties |
Classification |
Display and list properties |
Positioning |
Positioning and flow control of elements |
Printing |
Page break specification |
Filter |
Multimedia effects and transitions |
Pseudo-Classes and Other Properties |
The @import, cursor, and !important properties |
Table 1. Categories of CSS Properties
So, as it can be seen from the table, positioning is just one sub-category of properties available within CSS. However, because it is one of the most powerful, important, and useful aspects of CSS, it has acquired its own informal name. Indeed, the W3C addresses CSS positioning in an entirely separate specification, entitled Positioning HTML Elements with Cascading Style Sheets .
Some browsers (Microsoft Internet Explorer 4.0+, Netscape Navigator 4+) supports the ability to position HTML elements in x- and y-coordinates, as well as overlap elements in planes along the z-axis, which extends toward and away from the viewer in a Web document. This capability allows authors to place elements-images, controls, or text-exactly where they want on the 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 ActiveX Controls, and transparent images presents authors with a rich set of animation options.
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 provide the author with 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, you can control the precise position of elements by giving exact coordinates, or specifying 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. This is very powerful! The position of these elements can be recalculated and redrawn after the document is loaded without needing to reload the page from the server.
Controlling the position of an element uses several other layout control techniques. These include controlling the display of the object-that is, whether or not the element is displayed on the page, and how much of the element can be viewed by the user.
There are two 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. 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.
Overview of CSS Positioning Properties
Nine properties are considered part of CSS positioning and are listed in the following table:
Property |
Description |
Possible values |
Applies To |
position |
Makes elements positionable |
absolute | relative | static |
All elements |
left |
Left position of element |
length | percentage | auto |
Absolutely and relatively positioned elements |
top |
Top position of element |
length | percentage | auto |
Absolutely and relatively positioned elements |
height |
Height of element |
length | auto |
DIV, SPAN and replaced elements |
width |
Width of element |
length | percentage | auto |
DIV, SPAN and replaced elements |
visibility |
Controls visibility |
visible | hidden | inherit |
All elements |
z-index |
Layering control |
auto | integer |
Absolutely and relatively positioned elements |
clip |
Defines visible area of element |
shape | auto |
All elements |
overflow |
Specifies behavior on overflow |
visible | hidden | scroll | auto |
All elements |
Table 2. CSS Positioning Properties
How some of the properties are implemented depends on the hierarchical relationships between elements. For our purposes, the <BODY> tag is at the top of the hierarchy for a given HTML document. An element is the child of another element if it is nested within the tag of another element. The enclosing element is called the parent element. A sibling of an element is one that shares a parent. And the previous element refers to the element that immediately precedes an element in the source file, regardless of whether it has a parent, sibling, or no relationship.
The origin for a given element is where the 0,0 coordinate pair is located, from which the top and left properties are offset (we'll go into detail about this later). Each element has its own origin, which depends on the value of its position property as well as its location within the hierarchy of elements.
The flow of the document refers to the natural way the content "flows" into the browser window, which may or may not change (depending on the values of certain properties) as the browser window is resized.
Measuring Element Dimension and Location
The following diagram shows the document object model properties related to the dimension and location of elements. The example page contains a DIV element relatively positioned on the page. Since the overflow attribute of the DIV has been set to scroll and it contains more content than can be displayed within its limited client area, scroll bars are displayed.
1. Positioning Elements (Position Property)
The position property can be set to one of three values: absolute, relative, and static. The default is static. The position property is one of the more complex of the positioning properties because the interactions between the values of the position property, the top and left properties, and location of the element within both the hierarchy and the source file location can be tricky to understand.
Absolute Positioning (position: absolute)
An absolutely positioned element is always relative to either the next positioned parent or, if there isn't one, the BODY by default. 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, you set the attributes to 0 as follows:
<IMG SRC="sample.gif" STYLE=" left:0; top:0">
This positions the image within the border of the BODY element. Remember, there is a default border on the BODY, so if no border is desired, 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=" left:50;top:30;height:100;width:100">
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=" left:0; top:0">
</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 regardless of 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 would wrap normally based on the width of the element, and various inline elements contained within the positioned elements will be placed next to each other in source order according to the constraints of size and shape of the "container" (that is, the positioned element).
Calculating where an absolutely positioned element will be rendered is fairly straightforward. Absolutely positioned elements and their children are not part of the regular flow of the document, but are positioned independently, possibly overlapping other elements.
To calculate the origin of an absolutely positioned element, find the next parent element that is positioned either relatively or absolutely (that is, if a parent is static, skip it and go up the hierarchical chain to the next parent. If the <BODY> tag is reached, the traversal stops and it will be considered the parent element regardless of the value of its position property). The logical beginning of this parent element is the origin for the absolutely positioned element. That origin may or may not move as the window is resized, but the element will always be in the same place with respect to that origin.
The origin establishes the top left corner of a rectangle into which the absolutely positioned element and its children will flow.
The next three samples demonstrate the origin calculation for an absolutely positioned element.
<SPAN STYLE="position:static; background-color:#90EE90">
static green parent static green parent static green parent static green parent
<SPAN STYLE= " top:60px; left:60px;
background-color:#ADD8E6">
absolute blue child absolute blue child absolute blue child absolute blue child
</SPAN>
</SPAN>
Example #1: Absolutely positioned element with statically positioned parent
<SPAN STYLE=" background-color:#90EE90">
relative green parent relative green parent relative green parent
<SPAN STYLE= " top:60px; left:60px;
background-color:#ADD8E6">
absolute blue child absolute blue child absolute blue child absolute blue child
</SPAN>
</SPAN>
Example #2: Absolutely positioned element with relatively positioned parent
<SPAN STYLE=" background-color:#90EE90">
absolute green parent absolute green parent absolute green parent
<SPAN STYLE=" top:60px; left:60px; background-color:#ADD8E6">
absolute blue child absolute blue child absolute blue child absolute blue child
</SPAN>
</SPAN>
Example #3: Absolutely positioned element with absolutely positioned parent
In the first sample, because the parent is statically positioned, we "ignore" this and look to the next element in the hierarchy. In this case it's the BODY element, so we use the beginning of the BODY (that is, the beginning of the document) as the origin. In the other two examples, the parents of the absolutely positioned blue element are relatively and absolutely positioned, so they are used to establish the origin. So the blue text is positioned in the same place in the second and third examples (60 pixels below the top of the green element), which is slightly lower than in the first one (60 pixels lower than the top of the BODY element). In all three cases, the blue text is absolutely positioned, so no matter how you resize the window to make the green text flow, the blue text begins at the same location, and will overwrite the green text if necessary.
The way that the top and left properties are used also helps determine where an absolutely positioned element is positioned. If the element has its top and left properties set, the element will be positioned using these offsets with respect to the origin that we just talked about. If the top property is omitted or is set to auto (which is equivalent because auto is the default), the element will have its top edge beginning at the top of the last line of text of the parent element if it's text, and lined up with the top edge of the parent if it's an image. If the left property is omitted, the element will have its left edge positioned at the end of the last line of text of the parent element if it's text, and at the right edge of the parent if it's an image.
Following are four samples that demonstrate this. Be sure to resize the windows to see how changing a parent's position affects its absolutely positioned child. You can substitute the "relative green parent" text with an image to see the behavior when the parent is an image.
<SPAN STYLE=" background-color:#90EE90">
relative green parent relative green parent relative green parent relative green parent
relative green parent relative green parent relative green parent relative green parent
<SPAN STYLE=" background-color:#ADD8E6">
Absolute blue child with neither top nor left set.
</SPAN>
</SPAN>
Example #4: Absolutely positioned element with neither top nor left set
In example #4, because neither top nor left are set, the origin of the blue element is at the end of the green one. However, because the green element reflows when the browser window changes, this origin can actually move around. You'll see how this works if you make the browser window progressively narrower and watch the blue text.
<SPAN STYLE=" background-color:#90EE90">
relative green parent relative green parent relative green parent relative green parent
relative green parent relative green parent relative green parent relative green parent
<SPAN STYLE=" top:10px; left:50px; background-color:#ADD8E6">
Absolute blue child with top:10px and left:50px.
</SPAN>
</SPAN>
Example #5: Absolutely positioned element with top and left set
In example #5, because both the top and left are set, the origin for the blue element never moves no matter how narrow you make the browser window.
<SPAN STYLE=" background-color:#90EE90">
relative green parent relative green parent relative green parent relative green parent
relative green parent relative green parent relative green parent relative green parent
<SPAN STYLE=" top:10px; background-color:#ADD8E6">
Absolute blue child with top:10px.
</SPAN>
</SPAN>
Example #6: Absolutely positioned element with just top set
In example #6 we've got only the top set. So, according to the rules, that means the top value of the origin will never move - the blue element will always begin 10 pixels from the top of its (non-static) parent, the green element. But the left value for the origin is set to auto (by default, because it's not set at all), meaning to the end of the parent (green) element, so you'll see the left edge of the blue element's rectangle move as you make the browser window narrower.
<SPAN STYLE=" background-color:#90EE90">
relative green parent relative green parent relative green parent relative green parent
relative green parent relative green parent relative green parent relative green parent
<SPAN STYLE=" left:50px; background-color:#ADD8E6">
Absolute blue child with left:50px.
</SPAN>
</SPAN>
Example #7: Absolutely positioned element with just left set
Example #7 is just the reverse of example #6; in this case, the left side of the blue element's rectangle remains constant at 50 pixels, while the top varies depending on where the end of the green parent element is.
As we've already mentioned, the absolutely positioned element defines a new rectangle into which it and all of its children flow (and will draw over the top of other elements if necessary). The box begins at the top left corner of the element. You can set the width and height properties for the element. If no width property is defined, the rectangle to will extend to the right edge of the browser window. If a width is defined, it will retain that width even if the rectangle extends beyond the browser window; that part of the contents will therefore be obscured. If no height property is defined, the rectangle will extend as far down as necessary to display all of the contents. (Note that these descriptions for what happens when either the width or height properties are not defined represent default behavior; this behavior can be changed by setting the overflow property ).
<SPAN STYLE=" background-color:#90EE90">
Relative green parent.
<SPAN STYLE=" top:50px; left:50px; background-color:#ADD8E6">
absolute blue child absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child
</SPAN>
</SPAN>
Example #8: Absolutely positioned element with no width or height defined
Example #8 shows an absolutely positioned element without width or height defined. You can see as you make the browser window narrower that the rectangle into which the blue element flows always extends to the right edge of the browser window, reflowing downward if necessary.
<SPAN STYLE=" background-color:#90EE90">
Relative green parent.
<SPAN STYLE=" top:50px; left:50px; width:200px;
background-color:#ADD8E6">
absolute blue child absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child
</SPAN>
</SPAN>
Example #9: Absolutely positioned element with width defined
Example #9 demonstrates the use of the width property. In this case, the width of the blue element's rectangle remains the same regardless of the width of the browser.
Absolutely positioned elements and their children were not part of the regular flow, but instead create their own rectangle. Example #10 demonstrates this. The blue absolutely positioned element defines the origin of its rectangle to be at 50,50 and the width at 250 pixels. Since no height is set, the rectangle extends down as far down as necessary. The blue element has a red relatively positioned child, and you'll see that this child flows after the blue element but entirely within the left and right boundaries of the defined rectangle.
<SPAN STYLE=" background-color:#90EE90">
Relative green parent.
<SPAN STYLE=" top:50px; left:50px; width:250px;
background-color:#ADD8E6">
absolute blue child absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child absolute blue child absolute blue child
absolute blue child absolute blue child
<SPAN STYLE=" background-color:#FFB6C1">
relative red child relative red child relative red child relative red child
relative red child relative red child relative red child relative red child
</SPAN>
</SPAN>
</SPAN>
Example #10: Absolutely positioned element with relatively positioned child
Relative Positioning (position: relative)
Setting the CSS position attribute to "relative" places the element in the natural HTML flow of the document but 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: top:-3px">xyz</SPAN>
is "xyz".
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 BODY (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.
Figuring out where relatively positioned elements will end up is a little trickier. Relatively and statically positioned elements form the flow of elements in a document (as opposed to absolutely positioned elements, which are positioned as if on a layer above the other elements). To figure out what the flow of elements looks like, look through the source file, and mentally remove all absolutely positioned elements, including any children of those elements. Then position the remaining relatively positioned elements one after another - this is because for a relatively positioned element, the origin for element is at the end of the previous element in the flow (not in the source file), regardless of the hierarchical relationship.
Relatively positioned elements that are children of absolutely positioned elements were "removed" from the flow as explained above; they are still placed after the end of the previous element in the source, except that they are now relative to an absolutely positioned element that can be at any arbitrary place.
This is not easy to explain, but the examples should make it more clear. Example #11, Example #12, and Example #13 all display identically. Because all are relatively positioned elements with no top or left properties set, they simply flow one after another, regardless of their hierarchical relationship with each other.
<SPAN STYLE=" background-color:#90EE90">
Green relative element.
</SPAN>
<SPAN STYLE=" background-color:#ADD8E6">
Blue relative element.
</SPAN>
<SPAN STYLE=" background-color:#FFB6C1">
Red relative element.
</SPAN>
Example #11: Three same-level relatively positioned elements
<SPAN STYLE=" background-color:#90EE90">
Green relative element.
<SPAN STYLE=" background-color:#ADD8E6">
Blue relative child of green.
<SPAN STYLE=" background-color:#FFB6C1">
Red relative child of blue.
</SPAN>
</SPAN>
</SPAN>
Example #12: Three nested relatively positioned elements
<SPAN STYLE=" background-color:#90EE90">
Green relative element.
<SPAN STYLE=" background-color:#ADD8E6">
Blue relative child of green.
</SPAN>
</SPAN>
<SPAN STYLE=" background-color:#FFB6C1">
Red relative element.
</SPAN>
Example #13: Three relatively positioned elements; the second is a child of the first
Example #14 demonstrates how absolutely positioned elements are not part of the document flow. Even though the blue element is between the two relatively positioned elements in the source file, it does not affect the flow of the document. No matter how the window is resized, the blue element begins at the same location, and the red element flows directly after the green one.
<SPAN STYLE=" background-color:#90EE90">
green relative element green relative element green relative element
</SPAN>
<SPAN STYLE=" top:50px; left:50px; background-color:#ADD8E6">
Blue absolute element with top:50px and left:50px.
</SPAN>
<SPAN STYLE=" background-color:#FFB6C1">
red relative element red relative element red relative element
</SPAN>
Example #14: Relative, absolute, relative
Example #15 is similar except that the absolutely positioned blue element has a child. As you can see, the blue element and its child are pulled out of the flow of the document, while the red element again follows the green one.
<SPAN STYLE=" background-color:#90EE90">
green relative element green relative element green relative element
</SPAN>
<SPAN STYLE=" top:50px; left:50px; background-color:#ADD8E6">
Blue absolute element with top:50px and left:50px.
<SPAN STYLE=" background-color:#FFFFFF">
White relative child of blue.
</SPAN>
</SPAN>
<SPAN STYLE=" background-color:#FFB6C1">
red relative element red relative element red relative element
</SPAN>
Example #15: Relative, absolute with relative child, relative
Now, when we start setting the top and left properties of the relatively positioned elements, things get even more interesting. Let's say we have a relatively positioned element that has its top and/or left properties set. Another relatively positioned element that directly follows it in the flow calculates its origin as follows:
If the following element is a child of the first element, the origin of the following element is at the end of the first element.
If the following element is not a child of the first element, the origin of the following element is at the end of where the first element would have been if it hadn't had its position altered by the top and left properties.
Once again, let's look at some examples to make it easier. These are exactly the same as Example #11 and Example #12, but with the top property set on the center element. You'll recall that the three displayed identically before regardless of hierarchical relationship, but now they behave slightly differently.
<SPAN STYLE=" background-color:#90EE90">
Green relative element.
</SPAN>
<SPAN STYLE=" top:20px; background-color:#ADD8E6">
Blue relative element with top:20px.
</SPAN>
<SPAN STYLE=" background-color:#FFB6C1">
Red relative element.
</SPAN>
Example #16: Three same-level relatively positioned elements
In Example #16, the blue element is offset 20 pixels from the top of where it would have been. Because the following red element is not a child of the blue element, it is drawn at the end of where the blue element would have been, had we not adjusted its position using the top property.
<SPAN STYLE=" background-color:#90EE90">
Green relative element.
<SPAN STYLE=" top:20px; background-color:#ADD8E6">
Blue relative child of green with top:20px.
<SPAN STYLE=" background-color:#FFB6C1">
Red relative child of blue.
</SPAN>
</SPAN>
</SPAN>
Example #17: Three nested relatively positioned elements
Example #17 shows what happens now that the red element is a child of the blue; the position of the blue element has been altered, and the red element is drawn at the end of where the blue element now is.
Static Positioning (position: static)
We already discussed how statically positioned elements are ignored when calculating the origin for absolutely positioned elements. When mixed in with relatively positioned elements, statically positioned elements take the same origin as a relatively positioned element would; the primary difference is that you cannot set or offset the position of a statically positioned element using the top and left properties. A common mistake is to attempt to set these properties without first setting the position property to absolute or relative, (because the default for the position property is static) and then wonder why they have no effect. And because the top and left properties are meaningless when position is static, it follows that, as their name implies, a statically positioned element cannot have its position altered through script.
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 will reflow content should the user resize the browser. However, absolute positioning gives you the control to precisely place 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 build tables and use 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!
<HTML>
<HEAD><TITLE>Center the DIV</TITLE>
<SCRIPT LANGUAGE="JScript">
function doPosition()
</SCRIPT>
</HEAD>
<BODY onload="doPosition()">
<P>Some text in the beginning.</P>
<DIV ID=one STYLE=" top:10;height:200;width:200;
background-color:green">
Some text in the outer DIV
<DIV ID=two STYLE= " left:50;width:100;color:red;
border:red 2px solid">
Text in the inner DIV - its color should be red
</DIV>
</DIV>
</BODY></HTML>
Example #18:
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. In the example above, you 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 pos and pixel properties that provide alternate access to the top, width, and height properties.
The previous example can be expanded to manipulate multiple items on the page. Or, to animate this script, you might rework the scripting function on the onload of the document 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.
2. Element Visibility (Visibility Property)
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=" top:50;left:50;height:100;width:100;
visibility:hidden">
<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";
The visibility property of an element controls whether the element will be visible on the page, depending on whether it is set to visible or hidden. Note that even if the property is set to hidden, the space for the element within the flow of the document remains allocated and the invisible element continues to affect the document layout. This is contrast with the display property (which is categorized under the "Classification" properties even though it is functionally related to the visibility property); when the display property is set to none, the space allocated for the element in the document flow is relinquished.
This example demonstrates the difference between these two properties:
<HTML>
<HEAD><TITLE>Visibility Demo</TITLE>
<STYLE>
P
</STYLE>
<SCRIPT language=jscript>
<!--
function change_visibility()
else
}
function change_display()
else
}
-->
</SCRIPT>
</HEAD>
<BODY TOPMARGIN=0 BGPROPERTIES="FIXED" BGCOLOR="#FFFFFF"
LINK="#000000" VLINK="#808080" ALINK="#000000">
<P> Click the Button to change the visibility of the DIV
<DIV ID=MyDiv1 STYLE=" top:10;left:20;height:100;width:100;
visibility:hidden;background-color:blue">
</DIV>
<P> A paragraph below the DIV element<br>
<BUTTON onclick=change_visibility() style="background-color:blue;color:white">
Change Visibility
</BUTTON>
<HR>
<P> Click the Button to change the display of the DIV
<DIV ID=MyDiv2 STYLE=" top:10;left:20;height:100;width:100;
display:none;background-color:green">
</DIV>
<P> A paragraph below the DIV element<br>
<BUTTON onclick=change_display() style="background-color:green;color:white">
Change Display
</BUTTON>
</BODY></HTML>
Example #19:
The first button toggles the visibility property between visible and hidden, while the second button toggles the display property between none and the null string. (Note that we use the null string here because none is the only value that is currently explicitly supported. While specifying inline or block will appear to work for now, your pages will be rendered differently in the future when these values are supported. Null will always default to the default value, so it will display the element without breaking your code in the future.)
3. Clipping Regions (Clip Property)
You can set a clipping region for a positioned element by using the clip property. 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. It also does not affect the amount of space allocated for the element within the flow of the document.
For example, the following document uses clip to define a clipping region for the absolutely positioned DIV. The region, a 30-by-30 pixel square, displays only a portion of the text; the rest is clipped from view.
<HTML>
<HEAD><TITLE>Clip the DIV</TITLE></HEAD>
<BODY>
<DIV STYLE=" top:50;left:50;height:100;width:100;
clip:rect(0 30 30 0);background-color:green">
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>
Example #20:
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 30 30) causes the region not to display because the top and right have been defined as zero. The correct definition for a 30-by-30 clipping region based off the top left corner of the positioned object is to set clip:rect to (0 30 30 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)";
The next sample shows the syntax for setting the clip region initially, using an inline style sheet or a script (the JavaScript and VBScript versions are identical except for JavaScript's terminating semicolon).
Inline style sheet
<IMG ID=Olivia1 SRC="olivia1.gif"
STYLE=" top:0px; left:0px; width:136px; height:228px;
clip:rect(0 136 228 0)">
Script
Olivia1.style.clip = "rect(0 136 228 0)";
4. Overflowing Regions (Overflow Property)
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 property to either hide the overflow or enable scroll bars to let the user view it by scrolling.
The overflow property lets you choose what happens when the contents of an element do not fit within the rectangle defined by some or all of the top, left, height and width properties. There are four possible values for the overflow property, that function as follows:
Visible - Will expand size of the element to fit all of the contents. This is the default.
Hidden - Will clip size of the element to match its declared size.
Auto - Will put scroll bars on the element only if the contents exceed the stated size.
Scroll - Will put scroll bars on the element regardless of the size of the element.
You can set the value of the overflow property as in the following example:
<DIV STYLE=" top:60px; left:0px; width:100px; height:100px;
overflow:visible; background-color:white">
This is short.
</DIV>
<DIV STYLE=" top:60px; left:200px; width:100px; height:100px;
overflow:visible; background-color:white">
This is really really really really really really really really really really really long.
</DIV>
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.
<HTML>
<HEAD><TITLE>Scroll the Overflow</TITLE></HEAD>
<BODY>
<DIV STYLE=" top:50;left:50;height:100;width:100;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>
Example #21:
You can hide any overflow by setting the overflow property 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";
5. Z-Index Ordering (Z-Index Property)
The z-index property determines the order in which overlapping elements will be drawn, thereby determining the visible portion of each. By default, elements are drawn in the order in which they appear; the result is that elements appearing later in the source will be drawn over the top of earlier ones. 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 property. 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 z-index property lets you control the order in which you want things layered; elements are drawn from lowest to highest z-index values.
The following document uses z-index to stack text on top of the image.
<HTML>
<HEAD><TITLE>Stack the Image</TITLE></HEAD>
<BODY>
<P STYLE=" top:0; left:0">Text Over Image</P>
<IMG SRC="sample.jpg" STYLE=" top:0; left:0; z-index:-1">
</BODY>
</HTML>
Example #22:
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.
You can change the z-index dynamically by setting the zIndex property, as in this 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.
Dynamic Positioning
Any element that can be positioned either absolutely or relatively can have its position adjusted dynamically through script. This lets you create animations using any element that supports the position property. A major upside to using dynamic positioning to create animations is that they run entirely on the client side, and are therefore more efficient than many server-side solutions.
For example, in this sample, the blue text is a sibling of the red text. As we discussed earlier, a sibling is positioned relative to the end of the space the preceding element would have occupied had it not been positioned with the top and left properties. So the blue text stays put while the red text moves.
<HTML>
<HEAD><TITLE>Sample 22 - JavaScript version</TITLE>
<SCRIPT LANGUAGE="JScript">
<!--
var TextVisible;
function StartMove()
function MoveText()
} else
}
}
//-->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=#D3D3D3 onload="StartMove()">
<SPAN ID=MovingText STYLE=" background-color:#FFB6C1">
This text can whiz on and off the page.
</SPAN>
<SPAN STYLE=" background-color:#ADD8E6">
This text is a sibling of the moving red text.
</SPAN>
</BODY></HTML>
Example #23: Animate with siblings
On the other hand, in this sample, the blue text is a child of the red text. As our rules stated, that means it is supposed to be positioned relative to the actual position of the parent, and sure enough, the blue text faithfully follows the red text around, even though we never explicitly change its position.
<HTML>
<HEAD><TITLE>Sample 23 - JavaScript version</TITLE>
<SCRIPT LANGUAGE="JScript">
<!--
var TextVisible;
function StartMove()
function MoveText()
}
else
}
}
//-->
</SCRIPT>
</HEAD>
<BODY BGCOLOR=#D3D3D3 onload="StartMove()">
<SPAN ID=MovingText STYLE=" background-color:#FFB6C1">
This text can whiz on and off the page.
<SPAN STYLE="position: background-color:#ADD8E6">
This text is a child of the moving red text.
</SPAN>
</SPAN>
</BODY></HTML>
Example #24: Animate with children
Let's have a look at the JavaScript version of the Sample 22 (both samples move the text the same way; the only difference is the relationship between the two text elements). The HTML portion of the sample looks like this:
<BODY BGCOLOR=lightgrey onload="StartMove()">
<SPAN ID=MovingText STYLE=" background-color:#FFB6C1">
This text can whiz on and off the page.
</SPAN>
<SPAN STYLE=" background-color:#ADD8E6">
This text is a sibling of the moving red text.
</SPAN>
</BODY>
First, note that when we define the text, we set the position property to be relative. Remember, even though we don't want to explicitly position the text, position must be set to relative or absolute to be able to dynamically change the position. In the <BODY> tag we've specified that the StartMove() function should be called when the page is loaded. This function looks like this:
function StartMove()
We set a variable called TextVisible to 1 to tell ourselves that the text is currently visible. We just use this variable basically to keep track of which way the text is moving, on or off the page. Then we set a timer to call the MoveText() function every 50 milliseconds.
function MoveText()
} else
}
Each time this function is called, it checks the value of TextVisible. If it is 0, this means that the string is still not fully on the page and needs to be moved to the right, so it adds 10 pixels to the value of its left position (the pixelLeft property). It then checks to see if we are fully on the page (at which time the pixelLeft value will be 0), and if we are, sets the value of the TextVisible variable to 1. Then in future calls to MoveText(), we subtract 10 pixels from pixelLeft and therefore move the text to the left, off the screen. We keep doing this until we have moved 240 pixels to the left, then set TextVisible to 0 and the whole process will repeat itself infinitely. (Note the use of the pixelLeft property rather than the left property; we need to do this because we're manipulating the value, and left returns the value as a string where pixelLeft is an integer.)
Here is another example which 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.
<HTML>
<HEAD><TITLE>Glide the DIV</TITLE>
<SCRIPT LANGUAGE="JScript">
var action;
function StartGlide()
function Glide()
}
</SCRIPT>
</HEAD>
<BODY onload="StartGlide()">
<P>
With dynamic positioning, you can move elements and their content
anywhere in the document even after the document has loaded!
</P>
<DIV ID="Banner" STYLE="visibility:hidden; top:0; left:0">
Welcome to Dynamic HTML!
</DIV>
</BODY></HTML>
Example #25:
Note that you cannot dynamically change an element from nonpositioned to positioned. The position attribute should be set in the HTML source, as setting the position attribute in script will not work.
That's all there is to dynamically positioning elements - just decide what you want to do, think about how it will affect the position of other elements on the page, and change the position according to a timer, a user action, or whatever else meets your needs.
|