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?

3 Answers 3

10

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?

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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>

5 Comments

But why is the position value needed?
Because pseudo elements always have a default z-index relative to their parent element, rather than <html>. They will always appear 'behind' unless you override that behavior.
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?
@RobertC Your claim about z-index doesn't appear to be the case. Can you refer to any documentation?
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.