The Position CSS Property and interaction between elements

Position is a property difficult to use because the way its works depends on the nesting of tags and the type of position of their container.

To better understand its operation, graphs represents different scenarios depending on the position value of the container and the contained tags.

Understanding position with images

The position of a tag is defined by the top, bottom, left, right properties, when they are taken into account. And these values are relative either to the page or the container.

Values of position for a tag:

Static (default)

The elements come one after another from top to bottom and from left to right.
The properties of position (top, left, bottom, right, z-index) are ignored.

Relative

The position properties are taken into account, and relative to the previously displayed item.

Thus if we define: left: 100px, the tag will be offset 100 pixels from the container if this is the first tag in the container, or 100 pixels at the right of the previous element otherwise.

The tags are always inside the container when their position is relative.

Absolute

Absolute positions in the container tag, provided it is not static.

The values of positions are defined within the container. If no position attribute (top, left, etc...) is specified, the attributes are set to 0 by default, inside the container.

If the container is static:
- If content tags have no position values specified, they are displayed one after the other inside the container.
- If they are specified, the elements are positioned on the page as if they had fixed the position, but in the page rather than in the window.

Fixed

Positioning in the the browser window. When the page is scrolled, the object remains in the same position in the window, regardless of other tags.
The type of position of the container does not count here.

The items are displayed outside their container.

Inherit

Same type of position as the container. The values of position properties are taken into account as if the position was the same as the container. So it is static if no directive is passed.

Demonstration

This demo allows you to test different combinations. However, a dynamic change of positions does not work as well as a direct definition in the stylesheet.


In some cases, the colored squares may appear anywhere on the page.

The colored items have a width and a height of 64 pixels. The container has no properties of position, so it appears always after the previous element in the page.
The style elements:

blue
- top: 10px;
- left: 10px;
- background:blue;
green
- top: 40px;
- left: 100px;
- background:green;
yellow
- top: 40px;
- left: 200px;
- background:yellow;

Choose a type of position for the container in gray and colored elements it contains:

Container:     Items:
Top:10
Left:10
Top:40
Left:100
Top:40
Left:200

Reload the page after each test if needed.

References

© 2009-2014 Xul.fr