Better Semantic HTML with LESS

Posted by

Learn how LESS can help us create more semantic markup without bloating our CSS or spamming classes on every HTML-element.

Separation of concerns

CSS exists to give us better separation of concerns. We don't want our content to care about design. Writing semantic HTML means that you use the markup to describe the meaning of the content and not how it should be presented.

Limitations in pure CSS

It is quite possible to achieve almost complete separation between content and design with pure HTML and CSS, but it isn't optimal. We have to either bloat our HTML with tons of classes or repeat the same CSS code for many similar classes, meaning poor maintainability.

LESS extend to the rescue

With the extend-feature in LESS we can finally get semantic HTML and maintainable code at the same time.

Lets say that we have a webpage with three types of content:

  • Blog posts
  • News articles
  • Events

For each of these content types we want a page that lists the latest 10 items. We create CSS classes like “blog-post-list”, “news-article-list” and “event-list”. They will be very similar, but with some minor differences between them.

With pure HTML and CSS we are forced to either prepend a “content-list” class on the parent element, repeat the same CSS styles for all three classes or manually code the "extend". Usually we would choose to add the “content-list” class to each element, because that will give us the most maintainable code.

In Less we don't have to do this tradeoff. We can simply write:

.blog-post-list:extend(.content-list all) {
    /* custom code */

Read more about the extend feature in LESS

One class is better

<div class="blog-post-list">

is better than:

<div class="content-list blog-post-list">

because the content-list class is only added to help our CSS, it serves no purpose in describing the meaning of the content.

Put it in CSS if possible

While the same result is achieved by prepending the “content-list” class to your html element, and using extend will slightly increase CSS file size, reducing class-clutter will decrease the size of your HTML. CSS files are static and usually cached by the user, so the user will download them once per visit. The HTML files are dynamic and downloaded many times per visit.

Readability and maintainability

Looking at the “blog-post-list” class in the LESS-file will tell us that this extends the “content-list” class. In pure CSS this is not immediately clear since it is specified in the HTML. This approach also makes it easier to find all classes that extend another class.


The extend feature in LESS helps us write more semantic HTML with better maintainability compared to pure CSS.