CSS Position Property
The position property decides how an element is placed. Together with top, right, bottom and left, you can move it from its normal place.
| Value | Meaning |
|---|---|
static | Default. Normal flow. top, left and others have no effect |
relative | Moved from its normal place. Its old space stays reserved |
absolute | Removed from the flow, placed against the nearest positioned parent |
fixed | Placed against the browser window, stays while scrolling |
sticky | Normal until you scroll to it, then it sticks |
relative
.box { position: relative; top: 10px; left: 20px; }
absolute inside a relative parent
An absolute element is placed against its nearest ancestor that has a position other than static. So make the parent position: relative.
.parent { position: relative; height: 100px; background: #eee; }
.child { position: absolute; top: 10px; right: 10px; background: tomato; color: #fff; padding: 6px; }
Output in the browser
absolute: top 10, right 10
Parent with position: relative
fixed
.chat-button { position: fixed; bottom: 20px; right: 20px; }
A fixed element stays in the same place of the screen when the visitor scrolls. It is used for chat buttons and top bars.
sticky
.table-header { position: sticky; top: 0; background: #fff; }
Note:
To place a box over another box, use z-index. For page layouts prefer Flexbox or Grid. Position is best for small things, like badges and overlays.
Summary
relativeshifts an element,absoluteplaces it in a positioned parent.fixedsticks to the window andstickysticks after a scroll point.- Next: CSS z-index.
Congratulations! Chapter Finished. Learn more about the similar topics:
| Exercises & Assignments |
|---|
| Write CSS to centre a box horizontally using margin auto |
| Write CSS to create a horizontal navigation menu |