856

I am trying to use the :after CSS pseudo-element on an input field, but it does not work. If I use it with a span, it works OK.

<style type="text/css">
.mystyle:after {content:url(smiley.gif);}
.mystyle {color:red;}
</style>

This works (puts the smiley after "buu!" and before "some more")

<span class="mystyle">buuu!</span>a some more

This does not work - it only colors someValue in red, but there is no smiley.

<input class="mystyle" type="text" value="someValue">

What am I doing wrong? should I use another pseudo-selector?

Note: I cannot add a span around my input, because it is being generated by a third-party control.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
matra
  • 9,763
  • 4
  • 20
  • 31
  • 1
    If you have absolutely no control over the HTML, try changing the `border-color` of the `input` instead. I find it's more attention-getting. – Blazemonger Aug 26 '14 at 13:41

21 Answers21

1571

:before and :after render inside a container

and <input> can not contain other elements.


Pseudo-elements can only be defined (or better said are only supported) on container elements. Because the way they are rendered is within the container itself as a child element. input can not contain other elements hence they're not supported. A button on the other hand that's also a form element supports them, because it's a container of other sub-elements.

If you ask me, if some browser does display these two pseudo-elements on non-container elements, it's a bug and a non-standard conformance. Specification directly talks about element content...

W3C specification

If we carefully read the specification it actually says that they are inserted inside a containing element:

Authors specify the style and location of generated content with the :before and :after pseudo-elements. 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 'content' property, in conjunction with these pseudo-elements, specifies what is inserted.

See? an element's document tree content. As I understand it this means within a container.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
  • 144
    +1 Much better than the accepted answer. Thanks for the clear explanation of the standard itself. So much for `[required]::before { content "*"; color: red; }` :P – Kevin Peno Jun 16 '11 at 17:23
  • 101
    Tip: If you're having the problem with just a submit input like ``, use `` instead. The presentation is identical but the ` – flu Nov 23 '11 at 14:35
  • 16
    What about `
    `? I thought it wasn't a container element, but it could render `:after` and `:before` http://jsfiddle.net/Uf88j/1/
    – deathlock Oct 14 '12 at 08:55
  • 10
    @deathlock: that is indeed interesting. I would say it must be some kind of an anomaly and I wouldn't rely on it working cross browser or cross versions... HR is not a container element hence should not allow for pseudo elements. Even [W3C standard](http://www.w3.org/TR/html-markup/hr.html) says that it allows **no** content. And if you check for **void element** you [can see](http://www.w3.org/TR/html-markup/syntax.html#void-element) that these elements shouldn't have any content under any circumstances. Pseudo elements are content so expect future browser version to fail to display them. – Robert Koritnik Oct 14 '12 at 16:29
  • 1
    Note that "shouldn't (or more correctly, 'mustn't') have any content", is not "can't have any content". And if you do add content to a non-replaced void element via JavaScript, and the element is not hidden via `display:none` or similar, then that content will be rendered on the page. `:before` and `:after` pseudo-elements are just being consistent with that. – Alohci Aug 14 '13 at 08:20
  • 2
    The logic of the answer is not correct, as you can see e.g. from [appendix D](http://www.w3.org/TR/CSS2/sample.html) of the CSS 2.1 spec: it has a rule with the selector `br:before`. An element with EMPTY declared content still has content, it’s just empty, and you can append things to an empty string. There is no prohibition against `input:after`; it just has’t been implemented, or even defined well enough. – Jukka K. Korpela Oct 14 '13 at 11:10
  • @JukkaK.Korpela: But we could argue that *empty* content does not equal *element's document tree content* as it's not a sub-hierarchy of additional nodes. – Robert Koritnik Oct 14 '13 at 11:20
  • 1
    @deathlock @Robert I'll just leave it here: http://jsfiddle.net/52Y3j/1/ (---maybe it's because `hr` was a block element some time ago, even without content--- disregard that, needs more research) – Ale Jan 02 '14 at 18:28
  • Definitely some differences in implementation. Firefox will ignore br:after rules but it adheres to hr:after rules. – Spencer Williams Feb 03 '14 at 21:55
  • 9
    "*:before and :after render inside a container*" The :before and :after pseudo elements come "**before and after the content**". Not "at the beginning or end of" the container. *The spec does not mention a container*. With tags like `p` and `h1`, the content is within the tag, so before/after appear inside as well. With elements like `input` and `hr`, :before and :after would still appear before or after the content, but there is no container involved (especially for `input`). input:checked:before is widely used to indicate checkboxes being checked via css. – Radley Sustaire Jun 18 '14 at 22:10
  • 3
    @RadGH: Reasonable nitpick in the first part of your comment, but 1) `input` and `hr` are void elements by definition and there cannot possibly have content 2) I'm pretty sure the :before pseudo-element has nothing to do with your last statement. – BoltClock Jun 19 '14 at 09:30
  • @BoltClock Maybe by the "void" definition it makes more sense, but is still questionable as these elements do create "something", even if not traditional "content". I think the specs need to clear that up instead of debating it, though. Regarding `input:checked:before`, I've seen this used in a variety of places (including WordPress' core) to style a checkbox. You style the input as the "box", and the :before element as the "check". It's used often enough that it *must* be reliable, even if inputs are a void element. – Radley Sustaire Jun 19 '14 at 16:55
  • 1
    @RadleySustaire `input:checked::before` does not work reliably across browsers. Try this demo in Firefox: https://jsfiddle.net/bq1knxgb/. There is no pseudo-element in the DOM. – kleinfreund Mar 13 '17 at 08:53
  • 3
    @Radley Sustaire: [css-content-3](https://drafts.csswg.org/css-content-3/#content-property) now states that replaced elements do not have ::before or ::after pseudos, but doesn't say whether form elements count as replaced elements (and I remember a recent conversation pointing out that the HTML spec says that they actually don't, which blows my mind). Anyone that uses it - or worse, *relies* on it - must not test on, or support, any other browser than Chrome. Which isn't a surprise, of course. – BoltClock Nov 14 '17 at 04:21
  • 4
    @BoltClock Reading this years later I realize I must have been high or something - of course input:checked:before is not widely used but rather an accompanying label with :before is. I had provided incorrect information and appeared to believe it at the time. I wouldn't dare use a pseudo element on a checkbox now. – Radley Sustaire Nov 14 '17 at 06:26
  • @dallin you can position a search icon in an input box, as a background-image. – ANeves Mar 05 '19 at 12:36
  • There still can be ::placeholder pseudo element inside the input – Rauli Rajande Jul 15 '20 at 23:56
  • @kleinfreund Still doesn't work with firefox in 2020. Weird that there's an MDN doc specifically recommending it https://developer.mozilla.org/en-US/docs/Learn/Forms/UI_pseudo-classes#Using_generated_content_with_pseudo-classes – edddd Sep 16 '20 at 11:18
  • 1
    @JukkaK.Korpela CSS 2.1 Appendix D "is informative, not normative": The existence of rule `br:before` is meaningless, and only provided in this style sheet because that was (effectively?) what the then "current UA practice" was. – Oskar Grosser Dec 08 '22 at 03:05
283

:after and :before are not supported in Internet Explorer 7 and under, on any elements.

It's also not meant to be used on replaced elements such as form elements (inputs) and image elements.

In other words it's impossible with pure CSS.

However if using jquery you can use

$(".mystyle").after("add your smiley here");

API docs on .after

To append your content with javascript. This will work across all browsers.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Alex
  • 4,916
  • 1
  • 20
  • 15
  • Alex, I am using IE8 and latest FF, so IE7 is not an issue. I was seraching for any documentation about limiatation of :after, but was unable to find it. http://www.w3.org/TR/CSS2/generate.html states, that it is inserted after the current node in document tree so it should work in both cases. – matra Apr 07 '10 at 14:08
  • 3
    Unless you are building the page just for your own use a large percentage of the internet use those browsers still. The w3c spec says this yes; but as you well know browsers implement their own interpretation of the spec. Using :after on an input will only work in Opera 9+, but is not implemented in IE, FF, safari or chrome because of the way they internally construct the DOM - again it can't be done with pure CSS. – Alex Apr 07 '10 at 15:14
  • Thanks for the answer (BTW: I am building intranet application which wil be used by few internal users) – matra Apr 07 '10 at 18:35
  • 3
    I'm not sure if this was the case in April, but Webkit does support `:after` in general, though it doesn't support either `:before` or `:after` on inputs. – coreyward Dec 08 '10 at 17:09
  • 281
    As far as I understand W3C `:after` and `:before` pseudo elements, they can only be put on container elements. Why? Because they are appended **inside** that particular element. `input` is not a container. `button` for instance is hence you can put them on. Works as expected. Specification actually says: *before and after an element's document tree content* It explicitly says **CONTENT**. So an element must be a container. – Robert Koritnik Jan 11 '11 at 17:07
  • 36
    The next answer is way better.. Gives actual reason rather than talking about IE 7 (who cares) and jQuery (bad idea) – Rowan Jun 05 '14 at 18:07
  • Not properly the same thing. $().after() append some context after an element, but i think that with :after and :befor he want to insert insede the element something before and something after – Andrea_86 May 16 '17 at 16:22
  • "In other words it's impossible with pure CSS." Not 100% right, @Alex. See my solution below. –  Oct 29 '17 at 08:46
  • Plus, it's a bad pratice to add some text *as-is* in the DOM. You should wrap it in a span element. –  Oct 29 '17 at 10:02
  • The only `input` elements that are replaced are `type="image"`; all other `input`s are _empty elements_. – Oskar Grosser Dec 08 '22 at 02:52
73

Oddly, it works with some types of input. At least in Chrome,

<input type="checkbox" />

works fine, same as

<input type="radio" />

It's just type=text and some others that don't work.

Matt
  • 74,352
  • 26
  • 153
  • 180
vals
  • 61,425
  • 11
  • 89
  • 138
61

Here's another approach (assuming you have control of the HTML): add an empty <span></span> right after the input, and target that in CSS using input.mystyle + span:after

.field_with_errors {
  display: inline;
  color: red;
}
.field_with_errors input+span:after {
  content: "*"
}
<div class="field_with_errors">Label:</div>
<div class="field_with_errors">
  <input type="text" /><span></span> 
</div>

I'm using this approach in AngularJS because it will add .ng-invalid classes automatically to <input> form elements, and to the form, but not to the <label>.

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
51

:before and :after are applied inside a container, which means you can use it for elements with an end tag.

It doesn't apply for self-closing elements.

On a side note, elements which are self-closing (such as img/hr/input) are also known as 'Replaced Elements', as they are replaced with their respective content. "External Objects" for the lack of a better term. A better read here

CatalinBerta
  • 1,604
  • 20
  • 20
44

The biggest misunderstanding here is the meaning of the words before and after. They do not refer to the element itself, but to the content in the element. So element:before is before the content, and element:after is after the content, but both are still inside the original element.

The input element has no content in the CSS view, and so has no :before or :after pseudo content. This is true of many other void or replaced elements.

There is no pseudo element referring to outside the element.

In a different universe, these pseudo elements might have been called something else to make this distinction clearer. And someone might even have proposed a pseudo element which is genuinely outside the element. So far, this is not the case in this universe.

Manngo
  • 14,066
  • 10
  • 88
  • 110
  • 1
    I might not understand what you mean but if I do, pseudo elements work on hr? https://jsfiddle.net/demetriad/o49yn5hq/ – Christopher Jun 11 '19 at 14:01
  • 2
    @Chris That comes as a surprise to me, and on searching, to some others. I think that’s a quirk. `hr` has always been ambiguous from the CSS point of view, though you see that more in discussing colour. – Manngo Jul 10 '19 at 11:58
  • 1
    I have visited the universe where the `before` and `after` pseudo-elements are called `before-content` and `after-content`, and there are also `before-element` and `after-element` pseudo-elements which are quite nice and are supported in all browsers, however the food is positively awful and tequila was never invented. Be happy we live in this one. – Drew Feb 21 '23 at 20:42
42

I used the background-image to create the red dot for required fields.

input[type="text"][required] {
  background-image: radial-gradient(red 15%, transparent 16%);
  background-size: 1em 1em;
  background-position: top right;
  background-repeat: no-repeat
}

View on Codepen

vkjgr
  • 4,338
  • 1
  • 26
  • 19
24

You can't put a pseudo element in an input element, but can put in shadow element, like a placeholder!

input[type="text"] {   
  &::-webkit-input-placeholder {
    &:before {
      // your code
    }
  }
}

To make it work in other browsers, use :-moz-placeholder, ::-moz-placeholder and :-ms-input-placeholder in different selectors. Can't group the selectors, because if a browser doesn't recognize the selector invalidates the entire statement.

UPDATE: The above code works only with CSS pre-processor (SASS, LESS...), without pre-processors use:

input[type="text"]::-webkit-input-placeholder:before { // your code }
Unihedron
  • 10,902
  • 13
  • 62
  • 72
Shankar Cabus
  • 9,302
  • 7
  • 33
  • 43
  • 3
    Nice! Note that the placeholder pseudo element has limited property support: color, background, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height, text-indent, opacity. See http://css-tricks.com/almanac/selectors/p/placeholder/ – henry Dec 11 '14 at 22:05
  • Thanks for the hint. Just remember that everything inside the pseudo-element will disappear when the input box is filled in by user. That's an UX problem if all you wanted, like me, was displaying a `glyphicon-search` without touching markup. – Davi Lima Feb 24 '16 at 13:29
  • 2
    Some context on why this no longer works: https://bugs.chromium.org/p/chromium/issues/detail?id=582301 – Oliver Joseph Ash Nov 23 '17 at 17:20
22

A working solution in pure CSS:

The trick is to suppose there's a dom element after the text-field.

/*
 * The trick is here:
 * this selector says "take the first dom element after
 * the input text (+) and set its before content to the
 * value (:before).
 */
input#myTextField + *:before {
  content: "";
} 
<input id="myTextField" class="mystyle" type="text" value="someValue" />
<!--
  There's maybe something after a input-text
  Does'nt matter what it is (*), I use it.
  -->
<span></span>

(*) Limited solution, though:

  • you have to hope that there's a following dom element,
  • you have to hope no other input field follows your input field.

But in most cases, we know our code so this solution seems efficient and 100% CSS and 0% jQuery.

  • 2
    `input#myTextField ~ span:before {` much better, but span should have a class really to be more explicit like `.tick` or `.icon` – Val Aug 09 '18 at 14:31
  • @Val That selector would not work correctly, because `~` selects *every* preceding element, but you only want the first one. – Christoph Aug 18 '20 at 15:18
13

I found this post as I was having the same issue, this was the solution that worked for me. As opposed to replacing the input's value just remove it and absolutely position a span behind it that is the same size, the span can have a :before pseudo class applied to it with the icon font of your choice.

<style type="text/css">

form {position: relative; }
.mystyle:before {content:url(smiley.gif); width: 30px; height: 30px; position: absolute; }
.mystyle {color:red; width: 30px; height: 30px; z-index: 1; position: absolute; }
</style>

<form>
<input class="mystyle" type="text" value=""><span class="mystyle"></span>
</form>
Echilon
  • 10,064
  • 33
  • 131
  • 217
Morgan Feeney
  • 737
  • 7
  • 11
  • 1
    +1 -- This solution works well if you're using a plugin or framework that automatically adds validation classes to the element itself, but not to the parent label. – Blazemonger Aug 26 '14 at 13:38
5

According to a note in the CSS 2.1 spec, the specification “does not fully define the interaction of :before and :after with replaced elements (such as IMG in HTML). This will be defined in more detail in a future specification.” Although input is not really a replaced element any more, the basic situation has not changed: the effect of :before and :after on it in unspecified and generally has no effect.

The solution is to find a different approach to the problem you are trying to address this way. Putting generated content into a text input control would be very misleading: to the user, it would appear to be part of the initial value in the control, but it cannot be modified – so it would appear to be something forced at the start of the control, but yet it would not be submitted as part of form data.

Jukka K. Korpela
  • 195,524
  • 37
  • 270
  • 390
  • 3
    This is a comment, not an answer -- a rather long comment, but a comment nonetheless. – Blazemonger Aug 26 '14 at 13:39
  • @Blazemonger, it isn’t quite clear what was the question, but in any case, this answer addresses the same issue as the accepted answer, but in a more correct way. It’s not **impossible** to use generated content for `input` elements, just unspecified and browser-depending. – Jukka K. Korpela Aug 26 '14 at 15:34
5

As others explained, inputs are kinda-replaced void elements, so most browsers won't allow you to generate ::before nor ::after pseudo-elements in them.

However, the CSS Working Group is considering explicitly allowing ::before and ::after in case the input has appearance: none.

From https://lists.w3.org/Archives/Public/www-style/2016Mar/0190.html,

Safari and Chrome both allow pseudo-elements on their form inputs. Other browsers don't. We looked into removing this, but the use-counter is recording ~.07% of pages using it, which is 20x our max removal threshold.

Actually specifying pseudo-elements on inputs would require specifying the internal structure of inputs at least somewhat, which we haven't managed to do yet (and I'm not confident we *can* do). But Boris suggested, in one of the bugthreads, allowing it on appearance:none inputs - basically just turning them into <div>s, rather than "kinda-replaced" elements.

Oriol
  • 274,082
  • 63
  • 437
  • 513
5

The question mentions "input field". Although I believe the OP was referring to input field with type=text, ::after and ::before pseudocontent does render for several different types of input fields:

input::before {
    content: "My content" /* 11 different input types will render this */
}    

Here is a comprehensive demo of all input types, clearly showing which ones are compatible with (in this case) the ::before pseudoelement.

To summarize, this is a list of all of the input types that can render pseudocontent:

  1. checkbox
  2. color
  3. date
  4. datetime-local
  5. file
  6. image
  7. month
  8. radio
  9. range
  10. time
  11. week
CSSBurner
  • 1,565
  • 15
  • 13
4

You have to have some kind of wrapper around the input to use a before or after pseudo-element. Here's a fiddle that has a before on the wrapper div of an input and then places the before inside the input - or at least it looks like it. Obviously, this is a work around but effective in a pinch and lends itself to being responsive. You can easily make this an after if you need to put some other content.

Working Fiddle

Dollar sign inside an input as a pseudo-element: http://jsfiddle.net/kapunahele/ose4r8uj/1/

The HTML:

<div class="test">
    <input type="text"></input>
</div>

The CSS:

input {
    margin: 3em;
    padding-left: 2em;
    padding-top: 1em;
    padding-bottom: 1em;
    width:20%; 
}


.test {
    position: relative;
    background-color: #dedede;
    display: inline;
}

.test:before {
    content: '$';
    position: absolute;
    top: 0;
    left: 40px;
    z-index: 1;
}
  • Nice trick, but you could make a div stylized to "continue" the input. See this fiddle http://jsfiddle.net/ose4r8uj/31/ But you could also do it easier using bootstrap: http://getbootstrap.com/css/#forms-control-validation look for the "With optional icons" part. Even though, this has nothing to do with the original question. – Victor Ivens Mar 30 '15 at 17:24
  • 1
    FYI no good for :focus, :hover, etc. of the input because you can't target the parent element – jordanb Oct 29 '15 at 04:41
4

try next:

label[for="userName"] {
  position: relative;
}

label[for="userName"]::after {
  content: '[after]';
  width: 22px;
  height: 22px;
  display: inline-block;
  position: absolute;
  right: -30px;
}
<label for="userName">
 Name: 
 <input type="text" name="userName" id="userName">
 </label>
Alex Ovchinkin
  • 439
  • 1
  • 4
  • 6
3

If you are trying to style an input element with :before and :after, odds are you are trying to mimic the effects of other span, div, or even a elements in your CSS stack.

As Robert Koritnik's answer points out, :before and :after can only be applied to container elements and input elements are not containers.

HOWEVER, HTML 5 introduced the button element which is a container and behaves like an input[type="submit|reset"] element.

    <style>
    .happy:after { content:url(smiley.gif); }
    </style>

    <form>
    <!-- won't work -->
    <input class="happy" type="submit" value="Submit" />

    <!-- works -->
    <button class="happy">Submit</button>
    </form>
2

:before and :after only works for nodes that can have child nodes since they insert a new node as the first or last node.

Ruan Mendes
  • 90,375
  • 31
  • 153
  • 217
0

I found that you can do it like this:

.submit .btn input
{
   padding:11px 28px 12px 14px;
   background:#004990;
   border:none;
    color:#fff;
}

 .submit .btn
 {
     border:none;
     color:#fff;
     font-family: 'Open Sans', sans-serif;
     font-size:1em;
     min-width:96px;
     display:inline-block;
     position:relative;
 }

.submit .btn:after
{
    content:">";
    width:6px;
    height:17px;
    position:absolute;
    right:36px;
    color:#fff;
    top:7px;
}
<div class="submit">
  <div class="btn">
     <input value="Send" type="submit" />
  </div>
</div>

You need to have a div parent that takes the padding and the :after. The first parent needs to be relative and the second div should be absolute so you can set the position of the after.

ZygD
  • 22,092
  • 39
  • 79
  • 102
Patrick
  • 182
  • 1
  • 4
0

Summary

It does not work with <input type="button">, but it works fine with <input type="checkbox">.

Fiddle: http://jsfiddle.net/gb2wY/50/

HTML:

<p class="submit">
    <input id="submit-button" type="submit" value="Post">
    <br><br>
    <input id="submit-cb" type="checkbox" checked>
</p>

CSS:

#submit-button::before,
#submit-cb::before {
    content: ' ';
    background: transparent;
    border: 3px solid crimson;
    display: inline-block;
    width: 100%;
    height: 100%;
    padding: 0;
    margin: -3px -3px;
}
0

While the explanations that point out that the Firefox behavior of not allowing ::after and ::before content for elements that can't display any content are quite correct, it still seems to work perfectly fine with this rule:

input[type=checkbox] {
    -moz-appearance: initial;
}

As ::after is the only way to restyle a checkbox or radiobox without introducing more and unrelated markup like a trailing span or label, I think it's fine to force Firefox to allow ::before and ::after content to be displayed, despite not being to spec.

Alexander Gräf
  • 511
  • 1
  • 3
  • 10
0

Example of switcher with after and before just wrap your input on div block

.fm-form-control {
  position: relative;
  margin-top: 25px;
  margin-bottom: 25.2px;
}


.fm-switcher {
  display: none;
}
.fm-switcher:checked + .fm-placeholder-switcher:after {
  background-color: #94c6e7;
}
.fm-switcher:checked + .fm-placeholder-switcher:before {
  left: 24px;
}
.fm-switcher[disabled] + .fm-placeholder-switcher {
  cursor: not-allowed;
}
.fm-switcher[disabled] + .fm-placeholder-switcher:before {
  background-color: #cbd0d3;
}
.fm-switcher[disabled] + .fm-placeholder-switcher:after {
  background-color: #eaeded;
  border-color: #cbd0d3;
}

.fm-placeholder-switcher {
  padding-left: 53px;
  cursor: pointer;
  line-height: 24px;
}
.fm-placeholder-switcher:before {
  position: absolute;
  content: '';
  left: 0;
  top: 50%;
  width: 20px;
  height: 20px;
  margin-top: -10px;
  margin-left: 2px;
  background-color: #2980b9;
  z-index: 2;
  -moz-transition: all 0.15s ease-in-out;
  -o-transition: all 0.15s ease-in-out;
  -webkit-transition: all 0.15s ease-in-out;
  transition: all 0.15s ease-in-out;
  border-radius: 12px;
}
.fm-placeholder-switcher:after {
  position: absolute;
  content: '';
  left: 0;
  top: 50%;
  width: 48px;
  height: 20px;
  margin-top: -12px;
  background-color: #ffffff;
  z-index: 1;
  border-radius: 12px;
  border: 2px solid #bdc3c7;
  -moz-transition: all 0.15s ease-in-out;
  -o-transition: all 0.15s ease-in-out;
  -webkit-transition: all 0.15s ease-in-out;
  transition: all 0.15s ease-in-out;
}
<div class='fm-form-control'>
  <input class='fm-switcher' id='switcher_id' type='checkbox'>
  <label class='fm-placeholder-switcher' for='switcher_id'>
    Switcher
  </label>
</div>
colorswall
  • 188
  • 1
  • 4