Student-friendly HTML, CSS, and JavaScript reference with examples
The position property controls how an element is placed on the page.
A relative element stays in its normal spot, but you can nudge it with top, left, right, and bottom.
.box {
position: relative;
top: 10px;
left: 20px;
}
More importantly, relative creates a positioning context for its children.
An absolute element is removed from the normal flow and positioned relative to its closest relative (or absolute) parent.
.parent {
position: relative;
width: 400px;
height: 300px;
}
.child {
position: absolute;
top: 50px;
left: 100px;
}
The .child is placed 50px from the top and 100px from the left edge of .parent.
These properties set the offset from the parent’s edges:
.item {
position: absolute;
top: 0; /* flush with parent's top */
left: 0; /* flush with parent's left */
}
You can use px, %, or other units.
To place multiple elements on top of each other at the same position, give them all position: absolute with the same top and left inside a relative parent:
.card {
position: relative;
}
.card .background {
position: absolute;
top: 0;
left: 0;
}
.card .overlay {
position: absolute;
top: 0;
left: 0;
}
The last element in the HTML appears on top.