brentonstrine brentonstrine - 28 days ago 10
CSS Question

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

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
input
s 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

A similar outcome could be achieved by using a background image of a picture of an asterisk and setting the background of the label/input/the outer div and a padding of the size of the asterisk image. Something like this:

.required input {
   padding-right: 25px;
   background-image: url(...);
   background-position: right top;
}

This will put the asterisk INSIDE the text box, but putting the same on div.required instead of .required input will probably be more what you're looking for, if a little less elegant.

This method doesn't require an additional input.

I keep getting the odd upvote for this post. This answer was right for the OP but probably won't be the best option in most cases. The :after styntax is much better.

Comments