Use CSS to automatically add 'required field' asterisk to form inputs

brentonstrine picture brentonstrine · Jun 25, 2012 · Viewed 336.9k times · Source

What is a good way to overcome the unfortunate fact that this code will not work as desired:

<div class="required">
    <label>Name:</label>
    <input type="text">
</div>

<style>
    .required input:after { content:"*"; }
</style>

In a perfect world, all required inputs would get the little asterisk indicating that the field is required. This solution impossible since the CSS is inserted after the element content, not after the element itself, but something like it would be ideal. On a site with thousands of required fields, I can move the asterisk in front of the input with one change to one line (:after to :before) or I can move it to the end of the label (.required label:after) or in front of the label, or to a position on the containing box, etc...

This is important not just in case I change my mind about where to place the asterisk everywhere, but also for odd cases where the form layout doesn't allow the asterisk in the standard position. It also plays well with validation that checks the form or highlights improperly completed controls.

Lastly, it doesn't add additional markup.

Are there any good solutions that have all or most of the advantages of the impossible code?

Answer

mgherkins picture mgherkins · Jun 25, 2012

Is that what you had in mind?

http://jsfiddle.net/erqrN/1/

<label class="required">Name:</label>
<input type="text">

<style>
  .required:after {
    content:" *";
    color: red;
  }
</style>

.required:after {
  content:" *";
  color: red;
}
<label class="required">Name:</label>
<input type="text">

See https://developer.mozilla.org/en-US/docs/Web/CSS/pseudo-elements