10

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?

1

1 Answer 1

14

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.