twitter-bootstrap 使用 LESS 或 SASS 为 CSS 类名添加前缀

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17302333/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 17:25:59  来源:igfitidea点击:

Add prefixes to CSS class names using LESS or SASS

csstwitter-bootstrapsassless

提问by Kyle

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).

我正在尝试在一个包含 400 多个站点并使用以前的 CSS 类名称(我无法控制)的项目上使用 Bootstrap。我遇到了一些 CSS 名称冲突,我的解决方案是向 Bootstrap 添加前缀(例如 .row 到 .tb-row)。

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.

我熟悉使用 LESS 添加命名空间的方法,其中在类周围包裹了一个额外的类。不幸的是,这看起来并不能解决我的问题。

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?

是否有通过 LESS、SASS 或任何其他编译器的方法可以让我轻松地向 Bootstrap 中的所有现有类添加 tb- 前缀?

回答by imjared

You could probably do this with SASS

你可能可以用 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.
  • $命名空间:“tb”;
  • ? + f(或类似)以查找 CSS 文件中的所有类。你可能需要一个正则表达式(和一些试验+错误)来找到它们。
  • 添加.#{$namespace}-到所有类。

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 sawwith comments from people a lot smarter than I am. May come in handy for you though!

我不确定这是否是最好的方法,老实说,我只是从比我更聪明的人的评论中看到一个要点。不过可能对你有用!

回答by raygerrard

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

您需要直接修改引导程序代码,这是如何以更少的方式优雅地实现这一点的示例:

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

回答by Tim Guo

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-

我在 v3.1.0 中为所有引导类(LESS)添加了前缀“tb-”。所以在你编译less文件后你会得到类似“.tb-btn”的东西你可以在https://github.com/TimothyGuo/tb--prefix-for-Bootstrap-v3.1.0--LESS-fork我的项目