Question

I've always used :before in CSS to mean put content before the selector. I've never had any problems with this, however, I've stumbled across something that is confusing me where a selector's :before is appending inside the element instead of coming before it. I don't see why this is the case.

Here is a fiddle: http://jsfiddle.net/vMtct/1/

And here is the basic code:

<div class="block">
  <p>But this &lt;p&gt; will have content <em>before</em>.</p>
</div>
.block {
  margin: 0 auto;
  width: 250px;
  height: 250px;
  background: #ffffff;
  border: 1px solid #cccccc;
  padding: 50px; }
.block:before {
  background: #eeeeee;
  content: "Here is something that print's inside the selector";
  display: block;
  padding: 20px;
  margin-bottom: 20px; }
p:before {
  display: block;
  content: ">>>"; }
Was it helpful?

Solution

:before and :after are pseudo elements, that are not actually added to the DOM. They are inserted before the content of the element.

It is also therefore that they don't work on 'empty' (self closing) elements like <input /> or <img/>.

You could however get these pseudo elements to display 'outside' the element they are applied on, by positioning them absolute as demonstrated here: http://jsfiddle.net/vMtct/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top