CSS Position: static, relative, fixed, absolute

By Xah Lee. Date: . Last updated: .

The position property has 4 possible values:

div {position:static}

div {position:fixed}

div {position:relative}

div {position:absolute}

The CSS positioning is difficult to understand, but they are also quite powerful.

CSS Position Summary

「position」 ValueOwn LayerRelative To
staticno(Normal Flow)
relativenoRelative to its normal position
fixedyesRelative to window
absoluteyesRelative to its containing block. That is, the first parent that's not positioned static. If none found, then it's <html> tag.

position:static

The position:static is the default for all elements.

position:relative

Use position:relative to adjust a element's position relative to its normal position.

To specify the offset, use it together with:

AAA
BBB (relative position by left:10px)
CCC

Example:

CSS: Relative Position

position:fixed

Use position:fixed to specify the positioning of a element with respect to the window.

When a element has position:fixed, that element goes into its own layer. The normal flow of elements will flow as if that element doesn't exist.

Example:

position:absolute

position:absolute is like position:fixed, both makes the element go into its own layer.

What is the difference between position:absolute and position:fixed?

A “containing block” is effectively the first parent element that has a position value other than “static”. When no parent has any of “position” spec, then it is relative to the <html> element.

Example:

Overlapping and z-index

When a element goes into a layer, it may overlap with other element. To control which goes on top, you can use the attribute “z-index”. Like this: z-index:3. The larger the value, the more it is on top.

Can CSS z-index be negative?

yes.

What is the default value of CSS z-index?

0

CSS Layer Example

For examples of using a separate layer, see:

Reference

Visual formatting model#propdef-position

Like what you read? Buy JavaScript in Depth