The Basics of CSS Positioning
Positioning lets you take specific elements our of the normal document flow and change their behavior. Below is guide on how each one works, with examples to boot.
The CSS code looks pretty similar regardless of the type of positioning your design requires:
Types of Positioning
1. Static positioning (in-line by default)
By default, HTML elements are positioned in line with the normal document layout flow. Static position can be explicitly specified like this:
although it’s usually unneccesary.
2. Relative Positioning
Relative positions element relative to its in-line placement in the document. For instance in the example above, the Relative orange element is positioned 50px from the left and 10px from the top of its inline placement. Notice also that the space the element took up in it’s inline placement is still left over. The elements beneath it didn’t move in to fill the gap. That’s because it hasn’t actually been taken out of the document flow, so it’s spacing is still accounded for.
3. Absolute Positioning
Absolute positions element relative to its containing element. Absolute positioning takes the element out of the normal document flow, unlike relative. You can think of it rising up in a 3rd dimension, with the elements below filling with space it left behind. Speaking of the third dimension — we can control how elements are layers on top of each other with the z-index property. Z-index does not use measurements like px, just relative units. so 3 is above 2 and 300 is above 200, and they produce the same thing.
Top, right, bottom, and left positioning with abosolute specify the distance the element should be from each of the containing element’s sides.
4. Fixed Positioning
Fixed position positions elements relative to its the browser window. This one is often used on websites that have a chatbot or help window in the bottom righthand corner. It’s also useful of floating navs. Fixed positioning, like absolute, takes the element out of the document flow.
5. Sticky Positioning
Sticky positioning is the last CSS Positioning type. It was introduced about 4 years ago, and has only recently garnered enough browser support to be feasible to use. I think because of this it gets forgotten as a viable choice in the design process but it can be especially useful to display large indexes or directories.
Sticky positioning does what is sounds like, it sticks. It’s like a cross between in-line and absolute positioning. It originally assumes it’s inline position, however on scrolling, instead of scrolling up or down the page with the rest of the content, it will stick to a specific absolute position relative to it’s container.