Add prefixes to CSS class names using LESS or SASS

2019-03-20 06:28发布

I am trying to use Bootstrap on a project that encompasses 400+ sites and uses the previous CSS class names (which I have no control over). I've been running into some CSS name clashing and the solution for me is to add a prefix to Bootstrap (.row to .tb-row for example).

I am familiar with the method of adding a namespace using LESS, where an additional class is wrapped around the classes. Unfortunately, this doesn't look like it will solve my issues.

Is there a method via LESS, SASS, or any other compiler that makes it easy for me to add a tb- prefix to all existing classes in Bootstrap?

4条回答
我只想做你的唯一
2楼-- · 2019-03-20 06:33

Here is the fork of Bootstrap with class prefixes added. https://github.com/sneas/bootstrap-sass-namespace. Works pretty well for me.

查看更多
Emotional °昔
3楼-- · 2019-03-20 06:37

You would need to modify the bootstrap code directly, an example of how this could be achieved elegantly in less:

.prefixname {
    &-row { 
        ...
    }  
} 
查看更多
老娘就宠你
4楼-- · 2019-03-20 06:38

You could probably do this with SASS

  • $namespace: "tb";
  • ⌘ + f (or similar) to find all the classes in your CSS file. You're going to probably need a regex (and some trial+error) to find them all.
  • add .#{$namespace}- to all the classes.

Ideally, you'd get get something like this:

$namespace: "tb";

.#{$namespace}-myClass {
  background:pink !important;
}

.#{$namespace}-carousel-module {
  width: 25%;
}

compiled to

.tb-myClass {
  background:pink !important;
}

.tb-carousel-module {
  width: 25%;
}

"Easy" might be a stretch but "easier" seems fitting.

I'm not sure if this is the best approach, in honesty, I'm just ripping off a gist that I saw with comments from people a lot smarter than I am. May come in handy for you though!

查看更多
成全新的幸福
5楼-- · 2019-03-20 06:38

I've added prefix "tb-" to all the bootstrap class (for LESS) in v3.1.0. So after you compile the less files you will get something like ".tb-btn" You can fork my project at https://github.com/TimothyGuo/tb--prefix-for-Bootstrap-v3.1.0--LESS-

查看更多
登录 后发表回答