Monday, August 20, 2018

Namespacing Bootstrap 3 classes with prefix

I'm wondering what's the best way to namespacing bootstrap 3 CSS classes using a prefix.

This question isn't just about namespacing bootstrap so it applies only in a specific container (see here: How to namespace Twitter Bootstrap so styles don't conflict), but to litterally change all generated CSS classes using a predefined prefix.

I started to add the prefix pl- in the LESS files almost everywhere, but I must be missing some things because I break some part of the styling. So I'm looking for a smarter solution...

For instance, the .alert class in alerts.less must become .pl-alert.


The point of doing this is that I'm writing a plugin which can be used by other people (included in their website) and I must avoid that they override my styles by mistake (they probably have a .alert class which would be merged with mine and making a mess), so I want to avoid that by using a specific prefix.

Solved

I have been having the same issue and looking for some suggestions... I've found that the best way for me would be to have a namespace.less file in my bootstrap node project.

.namespace {
    @import (less) "../dist/css/bootstrap.css";
}

In my Gruntfile, I would create a task to compile another distribution. Something like this:

less: {
      compileCore: {
        options: {
          strictMath: true,
          sourceMap: true,
          outputSourceFiles: true,
          sourceMapURL: '<%= pkg.name %>.css.map',
          sourceMapFilename: 'dist/css/<%= pkg.name %>.css.map'
        },
        src: 'less/bootstrap.less',
        dest: 'dist/css/<%= pkg.name %>.css'
      },
      compileTheme: {
        options: {
          strictMath: true,
          sourceMap: true,
          outputSourceFiles: true,
          sourceMapURL: '<%= pkg.name %>-theme.css.map',
          sourceMapFilename: 'dist/css/<%= pkg.name %>-theme.css.map'
        },
        src: 'less/theme.less',
        dest: 'dist/css/<%= pkg.name %>-theme.css'
      },
      **compileNamespace: {
        options: {
          strictMath: true,
          sourceMap: true,
          outputSourceFiles: true,
          sourceMapURL: '<%= pkg.name %>.css.map',
          sourceMapFilename: 'dist/css/<%= pkg.name %>.css.map'
        },
        src: 'less/namespace.less',
        dest: 'dist/css/ml.<%= pkg.name %>.css'
      },** 
...

But there is some cleaning up I'd need to do afterwards. Specifically all the styles created by normalize.less and scaffolding.less.

I would create I grunt task using RegExp to replace the styles that start with .namespace html to be just html and the ones that start with .namespace body to be body.namespace

Then in my HTML markup, I'd just add the namespace class to the body tag.


No comments:

Post a Comment