简体   繁体   English

将外部样式表链接到特定的 HTML 元素

[英]Linking an external stylesheet to only specific HTML elements

Can I link an external stylesheet to only a specific element of an HTML file?我可以将外部样式表仅链接到 HTML 文件的特定元素吗?

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>

What you can do is compile your own bootstrap from the source.scss files.您可以做的是从 source.scss 文件编译您自己的引导程序。 See this related post: Limit the scope of bootstrap styles (except you don't actually have to fork bootstrap, that's overkill)请参阅此相关帖子: 限制引导程序 styles 的 scope (除非您实际上不必分叉引导程序,这太过分了)

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 ...因此 your-custom-bootstrap.css 的摘录对您来说可能如下所示:

#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您需要 go 通过设置构建步骤等过程 - 看看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有人完成并发布了它,但我在他们的回购协议中没有看到任何构建的资产,所以看起来你仍然需要设置构建工具,但至少它可以作为一个教程使用: https ://github.com/homeyer/scoped-twbs

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM