0

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: ">>>"; }
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
o_O
  • 5,527
  • 12
  • 52
  • 90

1 Answers1

5

: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/

Pevara
  • 14,242
  • 1
  • 34
  • 47
  • Ok. I get what you're saying. So basically you're saying in theory the examples I've given would look like
    "before content" content
    which is why it's inside the box and

    "before content" content

    which is why it appears actually before. Got it. I guess adding some styles to

    could have shown that.

    – o_O Jul 11 '13 at 00:46
  • I think I've only ever used :before on inline elements like that and so that was what was causing the confusion. Thanks. – o_O Jul 11 '13 at 00:49
  • The `:before` and `:after` pseudo-elements work on empty elements, too; e.g., CSS 2.1 has a rule with `br:after` in its default style sheet for HTML 4.01. For some empty elements (replaced elements), there can be limitations. But basically, for an empty element, these pseudo-elements cause content to be inserted right before or right after its content proper (which just happens to be empty). – Jukka K. Korpela Jul 11 '13 at 12:05
  • When using before and after and you use js append, does the js know about the before or after? I ask becasue the CSS is loaded first... – o_O Jul 11 '13 at 20:49
  • as far as I know, js can only access the DOM, so no pseudo elements. Also js applies styling directly to the element (style attribute) and it is not possible to add a pseudo element inside the style attribute. My guess would be **no**, unless somebody can prove me wrong... – Pevara Jul 11 '13 at 20:52
  • You can add styles inside – o_O Jul 18 '13 at 02:22