2
div {
    width: 100px;
    height: 100px;
    background: red;
}

div:before {
    content: "";
    width: 100px;
    height:30px;
    background: yellow;
}

Why isn't the before pseudo element showed above the div element when the position values (relative and absolute respectively) are not set?

Alex
  • 729
  • 2
  • 10
  • 24
LearningMath
  • 851
  • 4
  • 15
  • 38

3 Answers3

9

The ::before and ::after pseudo-elements are display:inline by default, which width and height will not affect.

You can set the pseudo-element to display:block.

div {
  width: 100px;
  height: 100px;
  background: red;
}

div:before {
  content: "";
  display: block;
  width: 100px;
  height: 30px;
  background: yellow;
}
<div></div>

View on JSFiddle

Also see What is the default display property of the :before and :after pseudo-elements?

ludovico
  • 2,103
  • 1
  • 13
  • 32
showdev
  • 28,454
  • 37
  • 55
  • 73
5

The default display property of both :before and :after is inline, so your width and height declarations have no effect. Change it to block and bob's your uncle:

div {
  width: 100px;
  height: 100px;
  background: red;
}

div:before {
  content: "";
  display: block;
  width: 100px;
  height: 30px;
  background: yellow;
}
<div></div>

jsfiddle example

j08691
  • 204,283
  • 31
  • 260
  • 272
3

You forgot to add position:absolute

 div {
  width: 100px;
  height: 100px;
  background: red;
}

div:before {
  content: "";
  width: 100px;
  height:30px;
  background: yellow;
  position: absolute;
}
<div></div>
Robert
  • 6,881
  • 1
  • 21
  • 26
  • But why is the position value needed? – LearningMath Apr 24 '18 at 19:27
  • Because pseudo elements always have a default `z-index` relative to their parent element, rather than ``. They will always appear 'behind' unless you override that behavior. – Robert Apr 24 '18 at 19:30
  • This also means that changing the z-index won't make it appear either? And why adding position absolute considers the width and height of the inline element? – LearningMath Apr 24 '18 at 19:32
  • 1
    @RobertC Your claim about `z-index` [doesn't appear to be the case](https://jsfiddle.net/pt2gbk3c/1/). Can you refer to any documentation? – showdev Apr 24 '18 at 19:33
  • My answer is specific to when `content` has no value though you could also set `display: block` for similar results. Typically though these pseudo elements require additional positioning (as borders, offsets, etc) so `position:absolute` is more commonly used in my experience. – Robert Apr 24 '18 at 19:36