我需要修改 bootstrap.css
以适应我的网站。我觉得最好创建一个单独的 custom.css
文件而不是直接修改 bootstrap.css
,原因之一是应该 bootstrap.css
重新包含我所有的修改。我会为这些样式牺牲一些加载时间,但对于我覆盖的少数样式来说,它可以忽略不计。
我该如何覆盖 bootstrap.css
以便 删除 锚点/类的样式?例如,如果我想删除 legend
的所有样式规则:
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #333333;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
我可以删除 bootstrap.css
中的所有内容,但如果我对覆盖 CSS 的最佳实践的理解是正确的,我应该怎么做?
明确地说,我想删除所有这些图例样式并使用父级的 CSS 值。所以结合 Pranav 的回答,我会做以下事情吗?
legend {
display: inherit !important;
width: inherit !important;
padding: inherit !important;
margin-bottom: inherit !important;
font-size: inherit !important;
line-height: inherit !important;
color: inherit !important;
border: inherit !important;
border-bottom: inherit !important;
}
(我希望有一种方法可以执行以下操作:)
legend {
clear: all;
}
原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用
!important
不是一个好的选择,因为您将来很可能想要覆盖自己的样式。这给我们留下了 CSS 优先级。基本上,每个选择器都有自己的数字“权重”:
在两种选择器样式中,浏览器将始终选择权重更大的一种。样式表的顺序仅在优先级相同时才重要——这就是为什么要覆盖 Bootstrap 并不容易。
您的选择是检查 Bootstrap 源代码,找出某些特定样式的确切定义方式,然后复制该选择器,以便您的元素具有同等优先级。但是我们在这个过程中有点失去了所有 Bootstrap 的好处。
解决这个问题的最简单方法是为页面上的根元素之一分配额外的任意 ID,如下所示:
<body id="bootstrap-overrides">
这样,您只需在任何 CSS 选择器前面加上您的 ID,立即为元素添加 100 点权重,并覆盖 Bootstrap 定义: