Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between relative positioned pseudo element and absolute positioned pseudo element

Tags:

css

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?

like image 443
shafkathullah Avatar asked Oct 29 '16 05:10

shafkathullah


1 Answers

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.

like image 111
jacefarm Avatar answered Sep 23 '22 15:09

jacefarm