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

Upgrade to access all content on Paulund

Members unlock all tutorials and snippets

Access to all downloadable content

Access to code examples before others

Sign Up Now

Already a member? Login here

Subscribe To The Weekly Newsletter

Get weekly updates to your email