How to namespace Twitter Bootstrap so styles don't conflict

This turned out to be easier than I thought. Both Less and Sass support namespacing (using the same syntax even). When you include bootstrap, you can do so within a selector to namespace it:

.bootstrap-styles {
  @import 'bootstrap';
}

Update: For newer versions of LESS, here's how to do it:

.bootstrap-styles {
  @import (less) url("bootstrap.css");
}

A similar question was answered here.


@Andrew great answer. You'll also want to note that bootstrap modifies the body {}, mainly to add font. So when you namespace it via LESS/SASS your output css file looks like this: (in bootstrap 3)

.bootstrap-styles body {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.428571429;
    color: #333333;
    background-color: white;
}

but obviously there will not be a body tag inside your div, so your bootstrap content will not have the bootstrap font (since all bootstrap inherits font from parent)

To fix, the answer should be:

.bootstrap-styles {
    font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
    font-size: 14px;
    line-height: 1.428571429;
    color: #333333;
    background-color: white;

    @import 'bootstrap';
}

Putting @Andrew, @Kevin and @adamj's answers together (plus a few other styles), if you include the following in a file named "bootstrap-namespaced.less", you can simply import 'bootstrap-namespaced.less' into any less file:

// bootstrap-namespaced.less

// This less file is intended to be imported from other less files. 
// Example usage:
// my-custom-namespace {
//  import 'bootstrap-namespaced.less';
// }

// Import bootstrap.css (but treat it as a less file) to avoid problems 
// with the way Bootstrap is using the parent operator (&).
@import (less) 'bootstrap.css';

// Manually include styles using selectors that will not work when namespaced.

@import 'variables.less';

& {
    // From normalize.less

    // Previously inside "html {"
    // font-family: sans-serif; // Overridden below
    -ms-text-size-adjust: 100%;
    -webkit-text-size-adjust: 100%;

    // Previously inside "body {"
    margin: 0;

    // From scaffolding.less

    // Previously inside "html {"
    // font-size: 10px; // Overridden below
    -webkit-tap-highlight-color: rgba(0,0,0,0);

    // Previously inside "body {"
    font-family: @font-family-base;
    font-size: @font-size-base;
    line-height: @line-height-base;
    color: @text-color;
    background-color: @body-bg;
}