iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Position

The position property controls how an element is placed in the document. Combined with top, right, bottom, left, and z-index, it lets you pull boxes out of the normal flow.

Five positioning modes

static default flow relative nudged from flow absolute vs. nearest positioned ancestor fixed vs. the viewport sticky scroll then pin Add top / right / bottom / left to move the box once you leave `static`. Use z-index to control stacking order between positioned elements.
Fig 1. How each value anchors the element.

What each value really does

ValueAnchored toTakes space?
staticNormal flow (default).Yes
relativeItself — moves visually but keeps its slot.Yes (original slot)
absoluteNearest positioned ancestor (or the viewport).No
fixedThe viewport — stays put when scrolling.No
stickyActs relative until it would scroll off, then fixed.Yes
Note: For position: absolute to anchor against a parent, that parent needs position: relative (or anything other than static).

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Position</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Pin this navbar to the top of the viewport.

.navbar { position: ; top: 0; }

Test yourself

Q1. Which positioning value anchors the element to the viewport, staying put on scroll?
Q2. For `position: absolute` to anchor against a parent, the parent needs…
Q3. Which value behaves relatively until it would scroll off-screen, then pins?

Discussion

Loading…