'Linking an external stylesheet to only specific HTML elements

Can I link an external stylesheet to only a specific element of an HTML file?

I tried this:

<div id="main">
  <!-- I don't want to style .alert from the external css -->
  <div class="alert alert-success" role="alert">I don't want to style this alert from the external css.</div>
  <div id="preview">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <!-- Specific Content Start - I want to style only this element with bootstrap -->
    <h1>Bootstrap 3 - Specific Content</h1>
    <!-- Specific Content End -->
  </div>
 </div>


Solution 1:[1]

What you can do is compile your own bootstrap from the source .scss files. See this related post: Limit the scope of bootstrap styles (except you don't actually have to fork bootstrap, that's overkill)

You'll end up with all the bootstrap rules prefixed with a certain selector - in your case, #preview ... so an excerpt of your-custom-bootstrap.css might look like this for you:

#preview .alert {
  padding: $alert-padding-y $alert-padding-x;
  margin-bottom: $alert-margin-bottom;
  border: $alert-border-width solid transparent;
  @include border-radius($alert-border-radius);
}

In part of your project files you'll have something like the following:

#preview {
  @import (less) 'bootstrap.css';
}

You'll need to go through the process of setting up the build steps, etc. - take a look at http://getbootstrap.com/getting-started/#grunt

Here's someone who's done this and published it, but I'm not seeing any built assets in their repo so it looks like you'd still have to set up the build tools, but at least it works as a bit of a tutorial: https://github.com/homeyer/scoped-twbs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community