Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to namespace Twitter Bootstrap so styles don't conflict

I want to use Twitter Bootstrap, but only on specific elements, so I need to figure out a way to prefix all Twitter Bootstrap classes with my prefix, or use the less mixins. I'm not experienced with this yet so I don't quite understand how to do this. Here's an example of the HTML that I'm trying to style:

<div class="normal-styles">   <h1>dont style this with bootstrap</h1>   <div class="bootstrap-styles">     <h1>use bootstrap</h1>   </div> </div> 

In this example, Twitter Bootstrap would normal style both h1s, but I want to be more selective about which areas I apply the Twitter Bootstrap styles.

like image 790
Andrew Avatar asked Dec 20 '12 06:12

Andrew


2 Answers

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.

like image 155
Andrew Avatar answered Oct 03 '22 12:10

Andrew


@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'; } 
like image 33
Kevin Avatar answered Oct 03 '22 11:10

Kevin