Positioning Elements with CSS
With the exception of floating elements right or left, we have thus far allowed our page elements to appear one after another down the screen. Using CSS, we can depart from this normal flow in order to:
- force an element to stay fixed in the same place in the browser window, even while the user continues to scroll further down the page.
- move elements up, down, right, or left relative to their normal position on the page.
- remove elements from their normal position and place them in a precise location within the page content.
- allow elements to overlap and to specify which appears in front and which appears in back.
Positioning Properties and Values
The CSS position property has four different values we will use:
- static – places the element in its usual location in the normal document flow. This is the default value.
- relative – keeps the element in the normal document flow but allows us to move it around relative to its normal location.
- absolute – removes the element from the normal document flow and allows us to place it in a specific location. It will scroll along with the surrounding page content.
- fixed – removes the element from the normal document flow and fixes it to a specific location in the browser window. Even when the page is scrolled, its location will remain the same.
This moves an element from the position it would be in normal flow, shifting it to the top, right, bottom, or left of where it would have been placed. This does not affect the position of surrounding elements; they stay in the position they would be in normal flow.
This positions the element in relation to its containing element. It is taken out of normal flow, meaning that it does not affect the position of any surrounding elements (as they simply ignore the space it would have taken up). Absolute positioned elements move as the user scroll up and down the page.
This is a form of absolute positioning that positions the elements in relation to the browser window, as opposed to the containing element. Elements with fixed positioning do not affect the position of surrounding elements and they do not move when the user scrolls up and down the page.