Shawn Taylor
Shawn Taylor

Reputation: 3969

Understanding :after and :before

http://jsfiddle.net/BtGRt/

Why contents are appearing inside div? Not on the left/right (before/after) the div?

Upvotes: 1

Views: 458

Answers (3)

scottheckel
scottheckel

Reputation: 9244

Looking at the spec, you can see that they are inserted in respect to the content not the element.

As their names indicate, the :before and :after pseudo-elements specify the location of content before and after an element's document tree content.

The :before and :after pseudo-elements inherit any inheritable properties from the element in the document tree to which they are attached.

For example, the following rules insert an open quote mark before every Q element. The color of the quote mark will be red, but the font will be the same as the font of the rest of the Q element:

q:before { content: open-quote; color: red }

Upvotes: 5

NekaraNef
NekaraNef

Reputation: 207

When you combine 'content' with :after and :before, it adds the content before or after the existing content. So, within the div. If you want it parse the additions around the div as a whole, you'd need something like

<div id="w">
 <div id="f">World </div>
</div>


#w:before{    
background: yellowgreen;
content: "Hello ";
}
#f{
width: 200px;
height: 200px;
background: gold;
margin: 100px;
padding: 100px;
}
#w:after{    
background: burlywood;
content: "StackOverflow";
}

Upvotes: 0

Chowlett
Chowlett

Reputation: 46685

Because :after and :before don't add psuedoelements after or before the element to which they are attached; they add them after or before that element's content.

See here for technical detail - the generated elements are the last / first child of the matched element.

Upvotes: 3

Related Questions