Skinning Bootstrap in Angular

So you’ve decided to make an Angular (2+, 5 at the time of writing) website and are set on using bootstrap (version 4.0.0 beta 3 at the time of writing) for your styling baseline, but want to spruce it up with some custom styles? You’ve come to the right place! Let’s begin…

Make sure when you generate your angular project, you do so with the flag --style=scss e.g.

If it’s too late and you already have a project on your hands that was not generated this way, no worries – just follow the instructions here to convert it.

Next, you’re going to want to install ng-bootstrap which adds the abstractions you need to use bootstrap components beyond simply styling, though strictly speaking it is not necessary for this (just highly recommended!). Follow the instructions on their website.

Now we want to install the bootstrap NPM package to get all of the SCSS files which we will need to skin our application, but that has peer dependencies on popper and jQuery, both of which are recommended by ng-bootstrap to not be used. That being said, we can’t really get around the fact that they’re set as peer dependencies by bootstrap so you will have to just install them without actually importing them and using them in your application. Run the following NPM install to get bootstrap:

This adds the directory /node_modules/bootstrap/scss  which is going to be of interest to us for the next bit. Make sure your .angular-cli.json is pointing to “styles.scss” instead of “styles.css” and then open said file.

Add the following line to your stylesheet to import all of bootstrap (or the parts of it you require):

At this point you basically have free-reign to follow the official docs from bootstrap on how to theme it. However, to give you a quick start and a simple idea I recommend taking the entire contents of /node_modules/bootstrap/scss/_variables.scss  and copying it to your own styles.scss  file above that import line I just mentioned – these are all the variables that set up colors, border radii, etc. that you’d probably likely be skinning. The reason you want to add them above is that bootstrap adds “!default” to each definition for these variables, allowing them to be overwritten by you to skin it. Next, remove all the !default mentions from your own style file, and add the following import on top of the whole thing to get access to some of the helper functions that the variables file uses:

Note that this may not be needed if you don’t plan on making heavy changes, and if you just plan to rewrite a few colors then you can just leave those relevant bits without importing the functions file.

You can now do something like:

Which will set your primary color to pink instead of the default blue on all the places it is used. Congratulations – your first bootstrap theme for an angular app!

0 Comments

Leave a Reply

Your email address will not be published.