Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add prefixes to CSS class names using LESS or SASS

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?

like image 803
Kyle Avatar asked Jun 25 '13 16:06

Kyle


People also ask

Which symbol is prefix for class name in CSS?

[ ] : is the container for complex selectors if you will... class : 'class' is the attribute you are looking at in this case. * : modifier(if any): in this case - "wildcard" indicates you're looking for ANY match.

Should I prefix my CSS classes?

Whilst prefixes can be considered overkill for small projects, the lack of proper CSS namespace support can lead to conflicts on larger projects, especially when using third-party libraries. You can easily avoid such conflicts by prefixing CSS classes with your initials or a short abbreviation of your project name.


2 Answers

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!

like image 94
imjared Avatar answered Oct 13 '22 00:10

imjared


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

.prefixname {
    &-row { 
        ...
    }  
} 
like image 42
raygerrard Avatar answered Oct 13 '22 01:10

raygerrard