Position Properties
In the previous lesson we learned how to use float to justify HTML elements with position. There are additional positional elements that provide flexibility and specificity for placing elements on a web page. Additional scripting classifications for positioning are:
- position: static;
- position: relative;
- position: absolute;
- position: fixed;
Static Position
Static is the default value, all elements will be static unless specified otherwise. This means the element is not placed and will adjust within the flow of the natural linear positioning on the webpage.
See the Pen Static by Stuart (@bystuart) on CodePen.
Fixed Position
An element can be fixed – it is fixed in one place and will not move regardless of any screen scrolling. It is commonly used for menus that stay at the top of a page when scrolling down a page. The element is taken out its normal flow and the space filled by the surrounding elements. It’s position is specified in relation to the viewport – the fancy name for the content area of your browsers!
See the Pen Fixed by Stuart (@bystuart) on CodePen.
Relative Position
By specifying the position as relative, you are saying that you want the element to move in relation to it’s normal position. After declaring that you want to move it (position: relative;) you then declare how much and in what direction you want to move. Just to be confusing they move in the opposite direction to what sounds normal. Since top: 20px;
will move it downwards, just keep in mind “I want to move it 20px from the top”!
The normal space that the element would take up if it wasn’t moved is left as an empty space, the surrounding elements will not fill the emptiness.
See the Pen Relative by Stuart (@bystuart) on CodePen.
Relative Position + Z-Index
As can be seen, elements will overlap if they are moved into the space of another. Elements are displayed in the order that they are written in your html. You can manipulate this by specifying a ‘z-index’. The default is zero, so giving the first element a higher z-index will make it appear on top instead:
See the Pen z-index by Stuart (@bystuart) on CodePen.
Absolute Position
When utilizing absolute positioning the element will not have dependency on other elements on the html document. An element with absolute positioning will be displayed in the exact location implemented by the code. The element with absolute positioning will not be affect the flow or placement of other elements on the web page, and it will not affect other elements. You can specify the alignment of your absolute positioning: top, right, bottom, and left.
See the Pen Absolute Positioning by jhoffmanbcc (@jhoffmanbcc) on CodePen.