ChatGPT解决这个技术问题 Extra ChatGPT

Can I use a :before or :after pseudo-element on an input field?

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.

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.

T
TylerH

:before and :after render inside a container

and 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.


+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
Tip: If you're having the problem with just a submit input like <input type="submit" value="Send"/>, use <button type="submit">Send</button> instead. The presentation is identical but the <button> is a container and thus supports :beforeand :after.
What about <hr />? I thought it wasn't a container element, but it could render :after and :before jsfiddle.net/Uf88j/1
@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 says that it allows no content. And if you check for void element you can see 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.
":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.
T
TylerH

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


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. 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.
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.
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.
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.
The next answer is way better.. Gives actual reason rather than talking about IE 7 (who cares) and jQuery (bad idea)
M
Matt

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.


@ANeves, it worked in Chromium for me, but not in Firefox.
Yes, type="submit" works as well.
B
Blazemonger

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: "*" }

Label:

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>.


It allows to add hover actions, like: input:hover+span:after{color: blue}. Upvote.
Why does this answer have so few upvotes? I think theoretical knowledge is important, but this solves the problem.
Nice option to go with in order to solve the problem.
C
CatalinBerta

: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


V
Veiko Jääger

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


This is really brilliant, nice job!
P
Pons Purushothaman

Pseudo elements like :after, :before are only for container elements. Elements starting and closing in a single place like <input/>, <img> etc are not container elements and hence pseudo elements are not supported. Once you apply a pseudo element to container element like <div> and if you inspect the code(see the image) you can understand what I mean. Actually the pseudo element is created inside the container element. This is not possible in case of <input> or <img>

https://i.stack.imgur.com/1yUox.png


M
Manngo

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.


I might not understand what you mean but if I do, pseudo elements work on hr? jsfiddle.net/demetriad/o49yn5hq
@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.
U
Unihedron

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 }

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 css-tricks.com/almanac/selectors/p/placeholder
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.
Some context on why this no longer works: bugs.chromium.org/p/chromium/issues/detail?id=582301
佚名

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: "👍"; }

(*) 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.


input#myTextField ~ span:before { much better, but span should have a class really to be more explicit like .tick or .icon
@Val That selector would not work correctly, because ~ selects every preceding element, but you only want the first one.
E
Echilon

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>

+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.
J
Jukka K. Korpela

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.


This is a comment, not an answer -- a rather long comment, but a comment nonetheless.
@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.
O
Oriol

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

s, rather than "kinda-replaced" elements.


K
Kapunahele Wong

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 jsfiddle.net/ose4r8uj/31 But you could also do it easier using bootstrap: getbootstrap.com/css/#forms-control-validation look for the "With optional icons" part. Even though, this has nothing to do with the original question.
FYI no good for :focus, :hover, etc. of the input because you can't target the parent element
A
Alex Ovchinkin

try next:

label[for="userName"] { position: relative; } label[for="userName"]::after { content: '[after]'; width: 22px; height: 22px; display: inline-block; position: absolute; right: -30px; }


K
Kevin Conroy

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>

HTML 4 actually introduced the
C
CSSBurner

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:

checkbox color date datetime-local file image month radio range time week


None supported in FireFox till now (version 102)
J
Juan Mendes

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


c
colorswall

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; }


Z
ZygD

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; }

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.


佚名

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;
}

A
Alexander Gräf

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.