Make the css of the widget overwrite theme css

Is possible to make bootstrap css “contextualized” inside a selector, i.e. bootstrap styles works inside that selector, and thanks to css specificity rules, there them take precence over other rules.

How to do:

First of all download bootstrap less. Let’s assume that this files are in 'bootstrap/less' folder.

Now create a new less file, let’s assume my-bootstrap.less.

In this file put

#my-widget-container .my-widget {
    @import 'bootstrap/less/bootstrap.less';
}

Compiling this less file*, let’s assume you obtain a file my-bootstrap.css. If you open this file, you’ll see that it is the full bootstrap environment, but where every rule is prefixed by '#my-widget-container .my-widget'.

At this point you can remove completely the bootstrap less files, and also your less file and only keep this my_bootstrap.css file (better if minimized), then instead of enqueuing original bootstrap you can enqueue that file, and you’ll have no issues with themes not using bootstrap.

However, if the theme is based on bootstrap your css file is redundant, so you should enqueue it only if bootstrap is not present:

function __construct() {
    // your stuff here
    add_action(
      'wp_enqueue_scripts',
      array( $this, 'register_plugin_styles' ),
      PHP_INT_MAX // highest priority
    );
}

public function register_plugin_styles() {

  global $wp_styles;

  $s = array_map( 'basename', wp_list_pluck($wp_styles->registered, 'src') );

  if ( ! in_array('bootstrap.css', $s ) && ! in_array( 'bootstrap.min.css', $s )  ) {
    // no one has registered bootstrap, let's register your 'my-bootstrap'
    wp_enqueue_style(
      'my-bootstrap', get_template_directory_uri() . '/my-bootstrap.css'
    );
  }  

}

Now what you have to do it’s just wrap the output of your widget with

<div id="my-widget-container">
  <div class="my-widget">

   YOUR WIDGET CONTENT GOES HERE

  </div>
</div>

* How to compile a less file into a css one is out of the scope of this answer and of this site, a simple Google search will give you any guidance, if you need it.

Leave a Comment