Html 如何防止我的样式被周围 div 上的另一种样式覆盖?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1196511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 00:25:38  来源:igfitidea点击:

How do I prevent my style from being overridden another style on a surrounding div?

htmlcsscss-selectors

提问by jergason

It seems elementary, but here is problem.

这看起来很初级,但这里有问题。

Stylesheet like so:

样式表像这样:

#Content h1, #Content h2, #Content h3, #Content h4, #Content h5, #Content h6 {
  color: #405679;
}

h3#issueHeader {
  color: blue;
}

HTML like so:

像这样的 HTML:

<div id="Content">
  <h3 id="issueHeader">In This Issue:</h3>
</div>

Instead of my issueHeader selector overriding the Content selector like I would expect, Firebug and my eyeballs show me that the color is inherited from the div, and the issueHeaderselector is overridden. Hunh?

不是我的 issueHeader 选择器像我期望的那样覆盖 Content 选择器,Firebug 和我的眼球告诉我颜色是从 div 继承的,并且issueHeader选择器被覆盖。嗯?

回答by Gavin Miller

You can throw the !importantattribute on h3#issueHeaderto force the browser to use that style

您可以抛出该!important属性h3#issueHeader以强制浏览器使用该样式

h3#issueHeader {
  color: blue !important;
}

However, it is only partially supported in IE6

但是,它在 IE6 中仅部分支持



此外,这仅应用作其他解决方案的最后手段。这是因为如果您网站的用户想要覆盖您的风格,那么重要就成为了一个有用的工具。

回答by dnagirl

css gives more weight to elements with more specificselectors. So if you want #Content h3not to override h3#issueHeader, give it another selector: e.g. #Content h3#issueHeader

css 赋予具有更具体选择器的元素更多权重。所以如果你不想#Content h3覆盖h3#issueHeader,给它另一个选择器:例如#Content h3#issueHeader

If your h1...hx elements are meant to be generally #405679, set them to that without the #Content selector. Then override them with a more specific selector when you need to.

如果您的 h1...hx 元素通常是 #405679,请将它们设置为不带 #Content 选择器的元素。然后在需要时使用更具体的选择器覆盖它们。

回答by Zack Marrapese

Try setting the selector as:

尝试将选择器设置为:

#Content h3#issueHeader {
    color: blue;
}

This should fix it.

这应该解决它。

回答by Vian Esterhuizen

If id="issueHeader" is duplicated that could do it.

如果 id="issueHeader" 重复,可以做到。

回答by easement

You are having what's called CSS specificity. Here's a good writup (using starwars to boot), that explains the basics in terms of points and how to calculate what will cascade:

您拥有所谓的 CSS 特异性。这是一篇很好的文章(使用 starwars 启动),它解释了点数方面的基础知识以及如何计算级联内容:

http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html