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

标签 html css twitter-bootstrap

我可以将外部样式表仅链接到 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>

最佳答案

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

您最终会得到所有以特定选择器为前缀的 Bootstrap 规则 - 在您的情况下,#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);
}

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

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

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

有人完成并发布了它,但我在他们的 repo 协议(protocol)中没有看到任何构建的 Assets ,所以看起来你仍然需要设置构建工具,但至少它可以作为一个教程:https://github.com/homeyer/scoped-twbs

关于html - 将外部样式表链接到特定的 HTML 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44030801/

相关文章:

java - NiFi - 如何根据子元素的值获取特定的 DOM 元素

css - 防止 DIVS 移动

html - 为什么 css "all: unset"在 MacOS 的 Safari 浏览器中运行异常?

html - Bootstrap 菜单总是折叠的问题

jquery - 使用 Bootstrap 3 对齐标题、图标和内容

ruby-on-rails - 造型 'collection_radio_buttons'

html - CSS:输入复选框和单选按钮外观

javascript - Hapi.js View 不加载 css 文件

css:如果分辨率低于 1024 x 786,则在网站主背景图像的底部和右侧获取空白

javascript - li 不显示在 ul 中