By default, elements are positioned on the page according to their normal place in the flow of the content. However, there will be times when you wish to have an element stay in a particular place on the page or near something else. You've learnt about the float property, but that can only do so much. The CSS position property allows you to locate an element in a particular place; a set distance from the top or bottom, left or right.
There are four types of positioning described here: The first is static, which is the default value. The others are relative, absolute and fixed. When you specify one of these non-default position values, the element is said to be positioned.
Description of each value
Some of the content below is positioned oddly for demonstration purposes. It has been placed within a container, shown in white.
- The default position setting.
- Relative to where it would be by default. The text you are reading is a specified distance to the right of where it would normally be.
- Located a set distance from the top or bottom and one side of its closest 'positioned' ancestor i.e. a parent or grandparent etc container that has relative, absolute or fixed positioning. If there are no positioned ancestors it will be located relative to the edges of the viewport and move as the page is scrolled.
- Located a set distance from the top or bottom and one side of the viewport. Does not move as the page is scrolled. For example, the header on this page is 'position: fixed'. Compare it to the header on other pages when you scroll upwards. It is positioned 'top: 0', i.e. zero distance from the top of the viewport. (Distance from one side is not needed because it occupies the full width)
There is also another position option, but it is beyond the scope of this course. Refer to the MDN site to learn about 'sticky' positioning.
How it looks in the CSS
The ruleset below is for specifying relative, absolute or fixed positioning.
position: value; [relative, absolute or fixed]
top: value; [distance from the top or bottom]
left: value; [distance from the left or right]