🎨 Customize bootstrap CSS to contain styles to an HTML element

Wesley Huber
2 min readJul 22, 2023

--

I’ve had this problem with many projects in my 10+ years as a software developer:

There is a pre-built site or application that does not use bootstrap and I want to add a new feature that relies on bootstrap CSS for it’s design.

If I import bootstrap’s CSS it messes up the styling of the entire application. Am I the only one who has ran into this issue? (Probably not)

How do we solve this problem?

LESS — a powerful CSS preprocessor that has been around since about 2010. This compiles and builds CSS code with variables and mixins. We can utilize these features to have LESS automatically add a class preceding all bootstrap classes like .container and .row

The resulting CSS looks like this:

Okay, let’s do this

Requirement: Node.js is installed on you machine

“directory” = folder

  1. Create a new directory, open a terminal or command line in that directory and install less (globally) using npm
npm install -g less

2. Download a version of Bootstrap. We’ll download Version 5 for this example.

3. Let’s use the bootstrap.css file that comes in the /css directory of the downloaded Bootstrap-version-dist project.

4. Copy that bootstrap.css file into your project directory.

5. Create a new file in your project directory called prefix.less

6. Add code similar to the following — note that the class .contained-bootstrap can be called whatever name you desire.

.contained-bootstrap {
@import (less) 'bootstrap.css';
}

7. Now on the command line, inside of your project directory run something like:

lessc prefix.less contained-bootstrap.css

Viola!

You now have a file called contained-bootstrap.css (the name of your css file can be anything) that you can import to your project and wrap with a container to isolate bootstrap.

<div class="contained-bootstrap">
<!-- Your Bootstrap only applies to content inside here-->
</div>

Let me know if this helps, or if you have any other ideas of how to contain bootstrap CSS 🤔

--

--