CSS

Add Required Asterisk With CSS

A red asterix is a common approach in website UX to show that a form field is required to be filled out by the using before submitting the form. Therefore when creating the form you will have to remember to add this in the HTML where you want the asterisk to appear which is commonly after the label of the form field.

<div class="form-group">
    <label class="control-label" for="username">Username</label> <span class="required">*</span>
    <input type="text" id="username" name="data[username]" required="required" class="form-control">
</div>

Then all you need to do is add a CSS class for required with the colour red.

.required
{
    color: red;
}

But what would happen if you forget to add the asterisk after a form field or if the form is dynamically created, here is a quick tip for automatically adding a red asterisk next to required fields just by using CSS.

Here is a standard HTML for creating a form field as you can see the label has a required class therefore we need to add an asterisk after this label.

<div class="form-group">
    <label class="control-label required" for="username">Username</label>
    <input type="text" id="username" name="data[username]" required="required" class="form-control">
</div>

Using CSS we search for all labels with a class required and use the :after pseudo class to add an asterisk and set the colour to red.

form label.required:after
{
    color: red;
    content: " *";
}

Add Asterisk After Textbox

If you would prefer to have the asterisk after the textbox then instead of searching for labels with a class of required you can search for input boxes with an attribute of required.

form input[required=required]:after,
form select[required=required]:after,
form textarea[required=required]:after
{
    color: red;
    content: " *";
}
Back to top

Comments

  1. Anon fiddle, https://jsfiddle.net/j4myL617/ I'm sure you cannot add pseudo generated elements to form controls, just labels and other standard HTML elements.

    You could (probably should) wrap the controls & apply the styling to the parent, but there are also alternative strategies for user experience, like limiting input to only required fields, or separating essential from non-essential with legend elements in fieldsets letting the user know expectations.

    Of course that extra data can and should be available to provide elsewhere, but then you already have the required fields filled, so required is set to ensure users don't blank them, maybe they are immutable at that point anyway.