Ever have a situation where adding a class or ID to your HTML markup is difficult? This is a common occurrence when working with content management systems or modules/plugins where the code is generated for you. A perfect example is Drupal, where adding classes often requires either writing a custom module to override the output, adding a custom template file, or hacking the module itself (don’t do this!).

If you’re using LESS with your theme, you can apply styles to your website markup without having to do any of the above. In this example, we’re going to turn a particular link class and make it look like a standard Bootstrap button.

Here’s our HTML markup for the link:

<a href="#" class="previous">‹ Previous</a>

To give it a button look, we would normally apply a few classes like so:

btn btn-primary">‹ Previous

Where we either can’t modify the markup or it’s too much trouble to modify and maintain, we can map with LESS mixins like so:

.previous {
    .btn,
    .btn-primary
}

The LESS compiler will render the CSS for .previous by importing the classes for .btn and .btn-primary, effectively doing the same thing as adding the classes to the markup, but without having to hack any modules or template files.

This is a good technique for styling a few elements of a site that are otherwise hard to modify. Using it extensively could lead to a lot of extra CSS code, possibly negatively impacting page load times.

Leave a Reply