Thunder Data Systems

Use CSS to Mark Fields as Required

Use CSS to Mark Fields as Required

Curious on how the pros handle marking required fields on their forms?  Wonder no more!  Below I’ll describe a technique I employ on my own forms to make marking required fields a simple and straight-forward process.  I will assume you have at least a basic working understanding of CSS, but even if you do not you should be able to still employ this technique.

First lets start with the HTML:

<ol>
<li class="required">
<label for="item1">Item One</label>
<input name="item1" id="item1" value="" />
</li>
<li>
<label for="item2">Item Two</label>
<input name="item2" id="item2" value="" />
</li>
<li class="required">
<label for="item3">Item Three</label>
<input name="item3" id="item3" value="" />
</li>
<li>
<label for="item4">Item Four</label>
<input name="item4" id="item4" value="" />
</li>
</ol>

This is a standard ordered list.  You may be curious why I choose to wrap my form elements inside a list?  It’s a recommended best practice, as is the use of the for attribute in the label.  If you want to learn more you can google for “form fields li best practices” to read the opinions out there.

Now to style our two required fields with *’s is a simple matter of some CSS code.  Our goal is to not actually use text in the html itself.  The reason we don’t want to do this is that “required” is not really content, it’s meta-information.  Marking a field as required or not therefore is something that should be treated as a style, not content.

If a client came back and asked to have the mark for required fields be treated differently, say instead of a * (star) they wanted an ! (bang), we only have to edit one little line of code.  What if they didn’t want a mark at all but instead wanted to have it highlighted with a red box?  You start to see the wisdom in handling this through a style than in the html itself.  We’ll need just a handful of styles to accomplish our goal:

 ol { list-style: none; }
li.required:after {
content: "*";
font-size: 18pt;
margin-left: -5px;
}
label {
display: block;
font-size: 14pt;
align: right;
margin-right: 0.5em;
}
input {
margin: 5px;
font-size: 14pt;
}

The :after pseudo-selector on the li element is a special selector for a marker.  You can think of a marker as a sub-element of the primary element that appears before or after it (in this case the li element with the class of required).  We could also select the marker that appears before using :before.  The resulting web page will look as below:

Leave a Reply

Your email address will not be published.