If you’re here, you know that Boostrap 3 is a powerful and flexible front-end framework. But you also know that embedding Bootstrap classes in your HTML is wrong. Sure, Bootstrap representational classes are easy to use, but what if you want to keep your markup clean?
1) Clean your markup
<div class="container">
<div class="row">
<div class="col-lg-8 col-md-8 col-sm-6 col-xs-12">
Main content
</div>
<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12">
Sidebar
</div>
</div>
</div>
After:
<div class="container">
<div class="introduction">
<section role="main">
Main content
</section>
<aside role="complementary">
Sidebar
</aside>
</div>
</div>
2) Using LESS to import Bootstrap core
Bootstrap 3 is built with LESS, a CSS preprocessor written in javascript. To unlock super powers, simply do:
-
- Create your own LESS stylesheet, let’s say style.less
- Import Bootstrap LESS files (all of them or individually if you don’t want to use all components)
// Import all Boostrap
@import "assets/bower_components/bootstrap/less/bootstrap.less";
// Or import components individually (for instance only grid and buttons):
@import "assets/bower_components/bootstrap/less/variables.less";
@import "assets/bower_components/bootstrap/less/mixins.less";
@import "assets/bower_components/bootstrap/less/grid.less";
@import "assets/bower_components/bootstrap/less/buttons.less";
Importing components individually gives you the opportunity to use only what you need. This means the resulting CSS file could be drastically smaller.
I recommend using Prepros to compile LESS stylesheets into CSS. The built-in live-reload is particularly handy.
3) Structure the code using Bootstrap Mixins
If you now take a look at your page, you’ll see that it has no style… the grid isn’t a grid anymore. So how to “restore” the way it looked? Mixins to the rescue!
First let’s create a handy mixin that helps playing with columns:
make-column(@large, @medium, @small, @tiny: 16) {
.make-xs-column(@tiny);
.make-sm-column(@small);
.make-md-column(@medium);
.make-lg-column(@large);
}
Then you would do the following:
.introduction {
.make-row();
}
[role="main"] {
.make-column(8,8,6,12);
}
[role="complementary"] {
.make-column(4,4,6,12);
}
Why should I care about semantic?
Making your Bootstrap code more readable for Search Engine bots (Google Bot for instance) will definitely help your SEO. But as this technique uses LESS, it also gives you more flexibility for styling elements. For instance, using variables or using anything Bootstrap mixins.
When should I use this technique?
Wondering when it’s worth spending time on this? In my opinion, this concept only applies to small sites.
For larger sites or web apps, I do not recommend using it as it’ll be a headache to maintain and the resulting CSS files will be bigger. I think it makes sense to use Bootstrap components if your project is big enough to raise concerns about maintainability.