CSS content generation before or after 'input' elements

Gui Prá picture Gui Prá · Jan 1, 2011 · Viewed 213k times · Source

In Firefox 3 and Google Chrome 8.0 the following works as expected:

<style type="text/css">
    span:before { content: 'span: '; }
</style>

<span>Test</span> <!-- produces: "span: Test" -->

But it doesn't when the element is <input>:

<style type="text/css">
    input:before { content: 'input: '; }
</style>

<input type="text"></input> <!-- produces only the textbox; the generated content
                                 is nowhere to be seen in both FF3 and Chrome 8 -->

Why is it not working like I expected?

Answer

Felix Kling picture Felix Kling · Jan 1, 2011

With :before and :after you specify which content should be inserted before (or after) the content inside of that element. input elements have no content.

E.g. if you write <input type="text">Test</input> (which is wrong) the browser will correct this and put the text after the input element.

The only thing you could do is to wrap every input element in a span or div and apply the CSS on these.

See the examples in the specification:

For example, the following document fragment and style sheet:

<h2> Header </h2>               h2 { display: run-in; }
<p> Text </p>                   p:before { display: block; content: 'Some'; }

...would render in exactly the same way as the following document fragment and style sheet:

<h2> Header </h2>            h2 { display: run-in; }
<p><span>Some</span> Text </p>  span { display: block }

This is the same reason why it does not work for <br>, <img>, etc. (<textarea> seems to be special).