The position property specifies the type of positioning method used for an element (relative
, fixed
or absolute
).
position: relative;
An element with position: relative;
is positioned relative to its normal position.
Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted to fit into any gap left by the element.
For example:
Say we have 3 <div class="box">
boxes inside a big box <div class="boxes">
<body>
<div class="boxes">
<!-- Make 2 classes for each, separate by space -->
<div class="box box-one"></div>
<div class="box box-two"></div>
<div class="box box-three"></div>
</div>
</body>
Color your boxes and set the second box to relative position:
.boxes {
border: 3px solid lightgrey;
}
.box {
width: 5rem;
height: 5rem;
}
.box-one {
background-color: gold;
}
.box-two {
background-color: tomato;
/* box-two is relative to its normal position */
position: relative;
left: 4rem;
bottom: 2rem;
/* Make box-two underneath the other boxes */
z-index: -1;
}
.box-three {
background-color: dodgerblue;
}
Note: The z-index
property specifies the stack order of an element. (the higher z-index
, the higher the stack order)
position: absolute;
An element with position: absolute;
is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed).
However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
==Note1: Absolute positioned elements are removed from the normal flow, and can overlap elements.==
Note2: When you set an absolute
postion, its parent has to be relative
.
For example:
.boxes {
border: 3px solid lightgrey;
/* Set parent box to relative */
position: relative;
}
.box {
width: 5rem;
height: 5rem;
}
.box-one {
background-color: gold;
}
.box-two {
background-color: tomato;
/* set to absolute */
position: absolute;
right: 0;
bottom: 0;
}
.box-three {
background-color: dodgerblue;
}
In the case above, box-two
will be display on another layer other than box-one
and box-three
. Hence, box-one
and box-three
won’t save the space for box-two
as it is in different universe~ (if you know multiverse lol)
position: fixed;
An element with position: fixed;
is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element.