Shafkathullah Ihsan Shafkathullah Ihsan - 1 month ago 6
CSS Question

Difference between relative positioned pseudo element and absolute positioned pseudo element

Consider the following three scenarios:

Scenario One:

div {
width: 100px;
height: 100px;
background-color: black;
}

div:before {
content: "";
width: 10px;
height: 10px;
background-color: darkred;
position: relative;
}


Scenario Two:

div {
width: 100px;
height: 100px;
background-color: black;
}

div:before {
content: "";
width: 10px;
height: 10px;
background-color: darkred;
position: absolute;
}


Scenario Three:

div {
width: 100px;
height: 100px;
background-color: black;
}

div:before {
content: "";
width: 10px;
height: 10px;
background-color: darkred;
display:block;
position: relative;
}


Scenario One (relative position) doesn't show the
darkred
pseudo element. But when it's changed into
position:absolute
the pseudo element is visible. Also, as shown in scenario three, when I added a
display:block
property to scenario one (relative position), the element is visible.

Why does
relative
position requires
display:block
and
absolute
doesn't?

Answer

A pseudo class such as :before has a default display CSS property value of inline.

Elements that are display: inline; are not "block-level" elements, and if they have no content, they do not take up any width. Thus, if you do not declare display: block; and you have an empty content declaration like content: "";, it will not take up any width at all in Scenario 1.

Elements that are position: absolute; are taken out of flow and are "block-level" elements with a default display CSS property value of block. Because of this, Scenario 2 renders the :before pseudo element, honoring its width and height declarations.

Scenario 3 is successful because the display property has been explicitly set to block.

You can see these default values being set by inspecting the :before element in your browser's web developer tools - see the "elements" inspector.