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:
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.
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 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.
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.
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.
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:
- top: 10px;
- left: 10px;
- top: 40px;
- left: 100px;
- top: 40px;
- left: 200px;
Choose a type of position for the container in gray and colored elements it contains:
Reload the page after each test if needed.