Why is * given more specificity than property inheritance in CSS?

不想你离开。 提交于 2021-01-27 17:51:06

问题


Put simply, I have a page with these two styles:

* { 
    color: black; 
}

div.error {
    color: red
}

And a page structure like:

<html>
...
<div class="error">
    <div class="row form">
        <div class="column">
            Error text.
        </div>
    </div>
</div>
...
</html>

You would expect "Error text" to be red, wouldn't you. But it is, in fact, rendered black in all browsers. Is this the expected behavior?

My second question, is contingent on whether this is the expected behavior. if it is, then why would a designer ever color every element on his whole website with "black" or some other color if that means it cannot be overridden with inheritance in specific places?

--EDIT--

The question is asked in the context of where you'd want a default color to be placed across the whole website, but wherever you want, you could say "this whole section inherits color #ffeeff". For example, a special form, contained by a divider of class "form." You don't want to label every sub-element of form with a special class like "white-text" to color everything white. You just want to set the "form" class's color and have it propagate to sub-elements.


回答1:


* is more specific than agent stylesheets (the default stylesheets that come with the browser), and inherited properties are nothing more than something like this:

div {
  /* ... */
  color: inherit;
  /* ... */
}

In the agent stylesheet, so your * with color: black is more specific than agent:div with color: inherit, thus it wins.




回答2:


It is the expected behavior, for the text to be red, you want to specify:

div.column {
  /* ... */
  color:red;
  /* ... */
}

Do check: (why) is the CSS star selector considered harmful? as suggested by 4castle.




回答3:


just do that instead:

<style>
* { 
    color: black; 
}

div.error {
    color: red
}
</style>
<div>
    <div class="row">
        <div class="column error">
            Error text.
        </div>
    </div>
</div>



来源:https://stackoverflow.com/questions/41840475/why-is-given-more-specificity-than-property-inheritance-in-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!