如何仅为页面单个div引入Bootstrap 3.3.1而不影响全局字体?
你遇到的核心问题是Bootstrap的全局CSS样式(比如对html、body的字体大小、字体族设置)会影响整个页面——哪怕你把<link>标签塞进某个div里也没用,因为CSS是全局生效的,和标签所在的位置无关。下面给你几个实用的解决方案:
如果你的项目用了预处理器(比如Sass),可以把Bootstrap的样式嵌套在目标类.bootstrap-test下面,这样所有Bootstrap样式只会作用在这个类内部的元素:
.bootstrap-test { @import "bootstrap"; // 导入Bootstrap的Scss源码 }
编译后,所有Bootstrap的选择器都会自动加上.bootstrap-test前缀——比如原来的.alert会变成.bootstrap-test .alert,完全不会干扰页面其他元素。
如果你不想用Sass,可以用工具给整个Bootstrap CSS的所有选择器加上.bootstrap-test前缀:
- 可以用在线CSS前缀工具,把Bootstrap的CSS代码粘贴进去,设置前缀为
.bootstrap-test,生成新的CSS后再引入。 - 或者用PostCSS的
postcss-prefix-selector插件,自动批量给选择器加前缀。
注意:处理后的全局样式(比如body { ... })会变成.bootstrap-test body { ... },如果不需要全局样式,可以只保留Alert相关的部分代码,进一步减少冗余。
如果你只需要Alert组件,没必要引入完整的Bootstrap CSS。可以提取Alert相关的必要样式,完全避开全局字体设置:
/* Alert基础样式 */ .bootstrap-test .alert { padding: 15px; margin-bottom: 20px; border: 1px solid transparent; border-radius: 4px; } .bootstrap-test .alert-warning { color: #8a6d3b; background-color: #fcf8e3; border-color: #faebcc; } /* 关闭按钮样式 */ .bootstrap-test .alert-dismissible { padding-right: 35px; } .bootstrap-test .close { float: right; font-size: 21px; font-weight: bold; line-height: 1; color: #000; text-shadow: 0 1px 0 #fff; opacity: .2; } .bootstrap-test .close:hover, .bootstrap-test .close:focus { color: #000; text-decoration: none; cursor: pointer; opacity: .5; } .bootstrap-test button.close { padding: 0; cursor: pointer; background: transparent; border: 0; -webkit-appearance: none; } /* Glyphicon警告图标样式(如果需要的话) */ .bootstrap-test .glyphicon { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } .bootstrap-test .glyphicon-warning-sign:before { content: "\e107"; }
然后只引入这个自定义CSS,再加上Bootstrap的JS(如果需要关闭Alert的交互功能),就能完美实现需求且不影响全局字体。
另外提个小错误:你的原始代码里把<link>和<script>放在<div>里是不符合HTML规范的,它们应该放在<head>(<link>)或者<body>末尾(<script>),不过即使放对位置,也不会改变CSS全局生效的特性哦。
内容的提问来源于stack exchange,提问作者Adya

