CSS Position Property:
The CSS Position Property: Everything You Need to Know
The CSS Position property is used to specify how the element will be displayed on the page. The top, right, bottom, and left CSS position properties determine the final location of the element. These properties only work if the position property is already established. They will also be affected by the position value.
CSS Position Types
Static Position
Static positioning is the default for every HTML element.It won’t be affected by certain properties that can make an impact on other CSS position types. No matter what value you associate with top, right, bottom, and left properties, they will not change, and neither will the z-index property.
div.container {
position: static;
border: 3px solid #73AD21;
}
Relative Position
At this value, the element follows the render flow but will be shifted relative to its initial position. To determine the amount of offset, set values for the top, right, bottom, and left properties. The other elements around the one in relative position aren’t affected, but there will be extra space where the element would have been. The z-index value should be set to auto unless you want a new stacking context. Essentially, this means you create a new set of layers that will be stacked based on that element.
div.container {
position: relative;
left: 30px;
border: 3px solid #73AD21;
}
Fixed Position
An element with position: fixed
; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.
div.nav{
position: fixed;
bottom: 0;
right: 0;
width: 300px;
border: 3px solid #73AD21;
}
Absolute Position
An element with position: absolute
; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Absolute positioned elements are removed from the normal flow, and can overlap elements.
div.container {
position: absolute;
top: 80px;
right: 0;
width: 200px;
height: 100px;
border: 3px solid #73AD21;
}
Sticky Position
An element with position: sticky
; is positioned based on the user's scroll position.
A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).
Internet Explorer does not support sticky positioning. Safari requires a -webkit- prefix (see example below). You must also specify at least one of top, right, bottom or left for sticky positioning to work.
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
background-color: green;
border: 2px solid #4CAF50;
}