Positioning Rules
Demo starter files
CSS has a few different rules for special positioning of elements. With the exception of floating elements, most of what we've done so far has only used the default setting - static
.
This is a good thing. Elements nest and styles cascade for a reason. Breaking that structure should be done with care.
While you can design an entire page by positioning every element using precise x and y coordinates, you'll also end up with a layout that scales very poorly to different screen sizes. This is one of the reasons why it's so difficult to make an effective drag and drop website editor.
Disclaimer aside, here are the different types of positioning, which can be very useful when the need arises!
The CSS property here is position
, and the options are static
, relative
, absolute
, fixed
, and sticky
.
Static
Static is the normal CSS document flow. The browser calculates how much space elements need based on their contents, and all of their positions are determined relative to one another.
Relative
With relative positioning, the browser still creates the space an element would normally occupy, but the element is shifted relative to that position using an x and y offset.
Relatively positioned elements are rendered in front of static content.
element {
position: relative;
top: -20px;
left: 20px;
}
Absolute
The element is removed completely from the document flow, so no space is created for it. Coordinates for x and y can then be explicitly set.
The context of the x and y positions are determined by one of two factors:
- The nearest ancestor element with a position setting other than static.
- If all of the element's ancestors have static positioning, the x and y position is based on the root element (
<html>
or<body>
). This effectively means the viewport, or browser window.
Absolutely positioned elements are rendered in front of static content.
element {
position: absolute;
top: 25px;
right: 25px;
}
Fixed
A fixed element is removed from document flow, so just like absolute, no space is created for it in the flow of other elements. A fixed element "sticks" to its position regardless of document scroll. The x and y position is almost always calculated relative to the viewport.
Fixed positioned elements are rendered in front of static content.
element {
position: fixed;
left: 0;
bottom: 0;
}
Sticky
When an element is set to position: sticky
, it behaves as relative positioning until it is scrolled to a set position in the viewport, then it behaves as fixed.
Sticky positioning is newer than the other positioning rules, but it has wide cross browser support. It's also typically used as a progressive enhancement, so it's usually ok if a browser happens to lack the feature.
element {
position: sticky;
top: 0;
}
These settings take a bit of practice and experimentation to understand. Download the starter files if you haven't already, and let's try them out!