Wrap a .Less CSS Definitions in a Namespace

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.

Less (css) - Can I re-declare a color variable that is referenced in other color definitions?

I assume, that you have at the beginning of the file your code from above and change somewhere afterwards your @gray-base color. Will all the other colors change?

Yes.

Have a look

Didn't know exactly how to make this stick, but if you comment the later @gray-base out, you see the color changing.

@Import of less files into a limited scope

According to the css-spec, the @import-declaration has to come before all other declarations in the css-file. So your @import inside the rule is expected to fail. I guess the @importing at the end of the file not failing is goodwill of the browser-vendors.

I guess LESS will abide by the same rules.

EDIT:
the question is, why do you want to have those styles scoped? With proper declarations, this should not be necessary.

LESS strictImports

The strictImports controls whether the compiler will allow an @import inside of either @media blocks or (a later addition) other selector blocks. See some of the comments from this closed issue with regards to that.

So with it set to true these are not allowed:

@media screen {
@import somefile.less;
}
.mySelector {
@import somefile.less;
}

How to use the same name classes but in separate styles

If using SCSS is an option, you could create a file that imports the two files but wraps each in its own namespace. Something like:

.bootstrap {
@import 'bootstrap.min.css';
}

.mdb {
@import 'mdb.min.css';
}

This file should go in the same directory as bootstrap.min.css and mdb.min.css and should have a .scss extension. After running the above through an SCSS compiler, you will have one CSS file that you can link to in your HTML file instead of bootstrap.min.css and mdb.min.css. For example, if your new compiled file is named combined.css, then you would replace the link tags in your question with this:

<link href="/build/css/site/combined.css" rel="stylesheet">

You could then use the styles in your HTML like so:

<div class="bootstrap">
<div class="btn btn-danger" >Standard Bootstrap Button</div>
</div>
<div class="mdb">
<div class="btn btn-danger" >Material Design Bootstrap Button</div>
</div>

Note that you must wrap your elements in a DIV (or other element) with a class of bootstrap or mdb to get the intended styling.



Related Topics



Leave a reply



Submit