Positioning
The position
property can break Normal flow. Unlike flex
, which makes a container where the normal flow rules don’t apply, position
can take an individual element out of the flow.
There are five values for position
.
position: static;
position: relative;
position: absolute;
position: fixed;
position: sticky;
See the MDN docs for position
for more, and for an interactive example.
Static
static
is how elements are positioned by default. The normal flow rules apply.
position: static;
Relative
relative
means the element shifts from where it would normally be positioned.
top
, bottom
, left
, and right
are used with position to specify where to move the positioned element.
position: relative;
top: 40px; left: 40px;
The yellow box is shifted 40px from the top and 40px from the left of where it started.
Absolute
Absolute positioned elements are out of the flow.
position: absolute;
top: 40px; left: 40px;
The yellow box is out of the normal flow, so the blue boxes act as if it isn’t there.
The top
and left
values are calculated from the parent element, instead of where the box started.
Fixed
Fixed position means that as you scroll, the element stays in the same spot on the screen, within the scroll window.
Like absolute
, fixed
elements are removed from the flow, and they calculate the top and right values from the containing element.
position: absolute;
top: 80px; left: 10px;
Scroll the example to see how the block stays in place while the rest of the page scrolls by.
Sticky
position: sticky
is really cool. It works like relative
, until the element reaches the edge of the scroll window.
Then, the sticky
element is ‘stuck’ to the top of the scroll window, until you scroll past the end of what it’s contained in.
position: sticky;
Scroll the example to see the effect.
Further Exploration: Position
MDN’s page on positioning provides more detail on the
position
property and how to use it.
Practice: Absolute Robot
🤖 The face has fallen off the robot!
Practice using the
top
,left
, andwidth
CSS properties andposition: absolute
to create a zany and fun face on the robot.