Learn CSS Position through a game
Slide a little box to the target by writing the position, top and left properties. What you type shows up live instantly.
Task: Put the box in the bottom-right corner
See each position type through a live animation. Once you get it, switch to «Practice» above and practice by writing the code yourself.
The default state
Every element starts out as static and sits in the normal flow. In this state top, left, right, bottom do nothing at all. To use them you first have to give it a different position.
/* doesn't move */ position: static; top: 30px; /* ignored */
Shifts from its own spot
A relative element shifts from its normal spot, but keeps occupying its place, so the elements next to it don't move (the gray box stayed put).
position: relative; top: 30px; /* down */ left: 40px; /* right */
Four directions
These properties push the element from its edges: top from the top (downward), left from the left (rightward), and right and bottom from the opposite edges. A negative value pushes in the reverse direction.
top: 20px; right: 20px; bottom: 20px; left: 20px;
Leaves the flow
absolute takes the element completely out of the flow (its neighbors fill the empty space) and places it relative to the nearest positioned ancestor. It's used to pin things to an exact spot from the edges.
position: absolute; top: 0; right: 0; /* top-right */
Relative to what?
An absolute element attaches to its nearest ancestor (whose position isn't static). If you give the parent relative, it becomes the «context» and the child is positioned inside that box.
.ota { position: relative; } .bola { position: absolute; top: 0; right: 0; }
Pinned to the screen
fixed pins the element to the viewport. No matter how far the page scrolls, it stays frozen in one place. That's how an always-visible chat button or a «back to top» button is made.
position: fixed; bottom: 16px; right: 16px;
Sticks when you scroll
sticky is a mix of relative and fixed. The element behaves normally until you scroll, and once it reaches the set spot it sticks in place. That's how section headings and menus are made.
position: sticky; top: 0;
Stacking order
When elements overlap, z-index decides the order: the element with the larger value appears in front. Important: it only works on a positioned (non-static) element.
position: relative; z-index: 10; /* to front */
Ready?
Now put your knowledge to the test: in the 16-level practice you write the code yourself and slide the box to the target.
Great!
The box landed on the target.