CSS Intermediate: Layout and Responsive Design
CSS Positioning and z-index
In this lesson you will
- Explain the five position values
- Place an element inside a positioned parent
- Control stacking order with z-index
Introduction
Usually elements flow down the page in order. Sometimes you need to break that rule: a badge in the corner of a card, a menu that stays on screen, a pop-up above everything. That is what the position property is for.
The five values
static: the default. The element follows the normal flow.relative: stays in the flow, but you can nudge it withtop,left, and so on. It is also the anchor for absolutely positioned children.absolute: removed from the flow and placed relative to its nearest positioned ancestor.fixed: placed relative to the browser window, and stays put when you scroll.sticky: scrolls normally until it reaches a set position, then sticks.
Quick quiz
Which value keeps an element fixed to the browser window while the page scrolls?
Relative and absolute together
The most useful pattern: make the parent position: relative, then place a child with position: absolute inside it.
If the parent were not positioned, the badge would jump to the corner of the page instead. That is the most common positioning surprise.
Sticky
A sticky element scrolls with the page until it hits the offset you set, then it stays. It is great for table headers and section titles.
Stacking with z-index
When elements overlap, z-index decides which is on top. A higher number is closer to the viewer. It only has an effect on positioned elements (and flex or grid items).
Change .a to z-index: 3 and run it again. Avoid huge numbers like 9999. A small, organised scale is easier to maintain.
Quick quiz
An absolutely positioned child appears in the wrong corner of the page. What is the likely cause?
Try it yourself
Add a small "Sale" tag to the top-left corner of the card below. Make the card position: relative and the tag position: absolute with top: 0; left: 0.
Summary
relativeanchors children,absoluteplaces against a positioned ancestor.fixedsticks to the window, andstickysticks after scrolling to an offset.z-indexorders overlapping positioned elements. Keep the numbers small.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading