引入Bootstrap后导航栏文字上移、字体样式变化该如何解决?
问题根因
Bootstrap内置了对nav、h4、ul、a等标签的默认样式规则,包括全局字体、行高、内外边距、链接默认样式等,优先级高于你现有自定义样式的部分规则,因此引入后覆盖了原有导航的样式表现。
解决步骤
- 修正全局行高和字体继承
在navigation.css最开头的全局规则和body规则中补充以下属性,覆盖Bootstrap的默认全局配置:
* { margin: 0; padding: 0; box-sizing: border-box; /* 新增以下属性 */ font-family: inherit; } body { /* 替换为你引入Bootstrap之前使用的字体即可,没有特殊需求可以写系统无衬线字体 */ font-family: system-ui, -apple-system, sans-serif; line-height: 1; /* 覆盖Bootstrap默认的1.5行高,避免文字偏移 */ margin: 0; }
- 覆盖导航元素的Bootstrap默认样式
在navigation.css中补充以下针对性样式:
/* 覆盖logo处h4的默认样式 */ .logo h4 { margin: 0; line-height: 1; font-weight: normal; /* 按需调整为你需要的字重 */ } /* 覆盖导航链接的默认样式 */ .nav-links a { text-decoration: none; /* 去掉Bootstrap默认的链接下划线 */ padding: 0; /* 去掉Bootstrap默认的链接内边距 */ line-height: 1; } /* 覆盖导航列表的默认样式 */ .nav-links { margin: 0; padding-left: 0; /* 去掉Bootstrap默认的ul左内边距 */ }
- 优先级兜底方案(可选)
如果以上修改后还有样式被覆盖,可以给导航标签增加自定义类名提高优先级:
- 先修改
navigation.html中的nav标签:
<nav class="custom-nav">
- 再将
navigation.css中所有导航相关的选择器前都加上.custom-nav前缀,例如:
.custom-nav { position: fixed; top: 0; width: 100%; display: flex; justify-content: space-around; align-items: center; min-height: 8vh; background-color: #4a495d; } .custom-nav .logo { /* 原有样式不变 */ } /* 其余导航相关选择器都按这个规则加前缀即可 */
内容的提问来源于stack exchange,提问作者Banaani Belle
相关产品推荐
相关产品推荐

