What is the difference between CSS position: static, absolute, relative?
One of the important aspects that would benefit you regardless of whether you use CSS alone or with the flexbox, grid layout design is what the static , absolute, relative
CSS positions mean.
static
— The element with position: static
is positioned according to the normal flow of the document. In this case, the two cards are stacked next to each other. The top
, right
, bottom
, left
and z-index
properties do not apply.
.container {margin-top: 20px;position: static;}.card_1 {position: static;margin-bottom: 20px;}.card_2 {position: static;margin-bottom: 20px;left: 0px;}
relative
— The element is positioned according to its own position in the normal flow of the document with the offset applied using thetop
, right
, bottom
, left
and z-index
properties. The element would leave a gap where its normal flow prior to the offset applied would have been.
.container {margin-top: 20px;position: static;}.card_1 {position: static;margin-bottom: 20px;}.card_2 {position: relative;margin-bottom: 20px;top: 300px;}
absolute
— The element is taken out of the normal flow of the document. Unlike position: relative
an absolutely positioned element doesn't leave a gap where its static position would have been. The sibling elements ignore the absolutely positioned element in their positioning. The offset is relative to the closest ancestor that doesn’t have a static
position. In this example, I have added a simple div with a wrapper
class around the two cards. Should I have set the left
property to a value less than the width of card_1
such as 220px, the two elements would overlap with card_2
stacked on top of card_1
unless specified otherwise (e.g. card_1
has a higher z-index
).
.container {margin-top: 20px;position: static;}.wrapper {position: relative;}.card_1 {position: relative;margin-bottom: 20px;}.card_2 {position: absolute;margin-bottom: 20px;left: 320px;top: 0px;}
References