Semantic CSS

Semantic CSS says that class names should describe an element rather than specify it. While we can’t and shouldn’t always use semantic class names, ie: when using CSS grids or similar concepts, in general it’s a good concept to strive for.

I will illustrate why semantic class names are a good thing with a simple example I recently encountered.

Good CSS classes are descriptive of the element itself and not the visual effect of the class. I recently modified some code that contained classes like w-80 (for width 80% !important) or ml-3 (for margin-left 3.0em). This made for things like:

<input class=”change-email-input” name=”email”>

A better way would have been to put the width 80% in the existing change-email-input class or to put in a new class like form-field. form-field describe what the element is, a form field, not what it should look like, width 80%.

I was asked to make some changes to this site to make it more responsive. At lower screen sizes it didn’t make sense to have this field at 80% width.

It would have been possible to add a @media query to change w-80 to another value, say 50%, but that would be really counter-intuitive. Removing the w-80 class to add a w-50 would necessitate manipulating the HTML or templates even though this could be easily avoided.

If the CSS class would have been called form-field making a media query to change it’s size would have been much less awkward. It also opens other options like adding a small-form-field to the element when on mobile while keeping the previous class.

Like in many other areas of programming, it’s a good idea to separate concerns and let the CSS files contain the style information while keeping the HTML files as declarative as possible by using semantic class names.

Here is a good article that goes over the concept of semantic class names in more detail: https://css-tricks.com/semantic-class-names/.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s