【问题标题】:Linking an external stylesheet to only specific HTML elements仅将外部样式表链接到特定的 HTML 元素
【发布时间】:2017-05-17 16:55:57
【问题描述】:

我可以将外部样式表仅链接到 HTML 文件的特定元素吗?

我试过了:

<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>

【问题讨论】:

  • 不,你不能那样做。只需为要覆盖的元素编写更具体的选择器。
  • 有没有 iframe 标签@ScottMarcus 的技巧或插件或解决方案?
  • @techLove 不,你没有。请不要提倡!important,因为众所周知这是一种糟糕的技术。您只需要创建一个更具体的选择器。它可以是基于id 的选择器或更接近元素的选择器。
  • 但是引导样式仍然存在。

标签: html css twitter-bootstrap twitter-bootstrap-3 stylesheet-link-tag


【解决方案1】:

您可以做的是从源 .scss 文件编译您自己的引导程序。请参阅此相关帖子:Limit the scope of bootstrap styles(除非您实际上不必分叉引导程序,这太过分了)

您最终会得到所有以特定选择器为前缀的引导规则 - 在您的情况下,#preview ...因此您的自定义引导程序.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);
}

在您的部分项目文件中,您将拥有如下内容:

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

您需要完成设置构建步骤等的过程 - 看看http://getbootstrap.com/getting-started/#grunt

有人做了这件事并发布了它,但我在他们的仓库中没有看到任何构建的资产,所以看起来你仍然需要设置构建工具,但至少它有点像教程:https://github.com/homeyer/scoped-twbs

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 2018-08-30
    • 2013-11-16
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 2013-12-08
    相关资源
    最近更新 更多