Add prefixes to CSS class names using LESS or SASS

强颜欢笑 提交于 2019-11-29 14:14:15

问题


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?


回答1:


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!




回答2:


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

.prefixname {
    &-row { 
        ...
    }  
} 



回答3:


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-



来源:https://stackoverflow.com/questions/17302333/add-prefixes-to-css-class-names-using-less-or-sass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!