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?
A pseudo class such as :before
has a default display
CSS property value of inline
.
Elements that are display: inline;
and position: relative;
are not "block-level" elements by default, 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
, which honors the width and height declarations.
You can see these default values being set by inspecting the :before
element in your browser's web developer tools - see the tools' "elements" inspector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With