Bootstrap components with alternate colors

2019-09-04 09:12发布

问题:

Is there a recommended way to have 2 Bootstrap components with different color sets?

For example, two nav-tabs, one in a dark theme, and another in a light theme.

Preferably something like:

<div class="dark"><ul class="nav nav-tabs"> ... </ul></div>
<header>...</header>
<div class="light"><ul class="nav nav-tabs"> ... </ul></div>

But something like this might be fine:

<ul class="dark-nav dark-nav-tabs"> ... </ul>
<header>...</header>
<ul class="dark-nav light-nav-tabs"> ... </ul>

I would rather include 2 Bootstrap CSS files, one with dark variables.less and one with light colors, but have the styles prefixed in some kind of namespace. Ideally I would want to minimize the risk of accidentally typing or something. Having a around the dark areas would be easier.

回答1:

In LESS, you can import other .less/.css files wherever you want, also inside rulesets:

#dark {
   @import "style-dark.less";
}

#light {
   @import "style-light.less";
}

Combining this with Bootstrap options that let you customize colors, you should be able to achieve the desired results, simply importing two generated files into appriopriate rulesets.



回答2:

It seems strange for me to @import "bootstrap.less" under a class cause bootstrap.less contains the import for every file of Booststrap's css. See also: Is it possible to apply bootstrap for a div only, using CDN?

Try to take a look how Bootstrap do this: https://github.com/twbs/bootstrap/issues/10332

The thinking behind this is that the pure .navbar class only provides layout styles etc, and >all colors are applied by the modifier classes.

For example a button has two classes always .btn for layout styles and .btn-* b.e. btn-error for colors. I think you could use the same strategy.

You should use something like:

<ul class="nav nav-dark nav-tabs nav-tab-dark"> ... </ul>

Where you define in for example custom-nav.less (imported in bootstrap.less):

.nav-tabs-dark > li.active > a, 
.nav-tabs-dark > li.active > a:hover, 
.nav-tabs-dark > li.active > a:focus
{
   background-color: #000;
   color: #fff;
}

etc.