matthew hawthorne

Extending Bootstrap CSS with Sass

Overview

I recently redid this site after not touching it for 10 years. I had used Bootstrap and Sass for some side projects, and wanted the ability to create my own CSS classes which “extend” Bootstrap classes (like .p-5 for spacing).

It took me a few hours to figure out, but what I have works, so if you’re struggling with it, read on.

Step 1. Install Sass gem

I use Jekyll to build this site, so I’m also using Bundler as a quick way to manage the jekyll gem and dependencies.

So I add bootstrap to my Gemfile, then run: bundle install

Step 2. Copy Sass files into your project

If you run bundle show bootstrap you’ll see the location of the Bootstrap Sass files.

I then copied those files into my local project so they sit alongside my site’s Sass files:

rsync -aP $HOME/.rvm/gems/ruby-2.7.0/gems/bootstrap-4.4.1/assets/stylesheets/ ${MY_LOCATION}

I’m using RVM so my gems go under the ~/.rvm dir. Your gems may go elsewhere.

Step 3. Ensure you are using Dart Sass

This was the most confusing part for me.

I modified my CSS to extend from the Bootstrap files, but nothing was happening. After some research I saw that the @use keyword only works with Dart Sass, which is the “primary implementation” of Sass.

It looks like Dart Sass is the one managed by NPM, so this installed it:

npm install –force -g sass

Now if I try to see all of the sass installations on my box:

> type -a sass

sass is $HOME/.rvm/gems/ruby-2.7.0/bin/sass
sass is /usr/local/bin/sass

Sass versions for both:

> $HOME/.rvm/gems/ruby-2.7.0/bin/sass -v
Sass 3.5.4 (Bleeding Edge)

> /usr/local/bin/sass --version
1.26.3 compiled with dart2js 2.7.1

Although the latter version looks “older”, it is the one you want. I hardcoded the location in my build file. Maybe you can just uninstall the older one.

Step 4. Add @use and @extend statements

Now, I can actually do stuff.

I extended bootstrap at the top of my Sass file:

@use "bootstrap";

Then I added a .code class (used by all of the code blocks in this post) which extends Bootstrap classes for background color, text color, and padding:

.code {
    @extend .bg-dark;
    @extend .text-light;
    @extend .p-3;
}

This is just an example, and probably the tip of the iceberg - from here you can extend whatever you want.

I don’t have a firm grasp of what I’m doing, but it seems to work. If you’re stuck, hopefully this helps you along. I believe in you.

© matthew hawthorne 2011-2023