* CSS规则如何比类或ID样式规则更具体?

时间:2011-09-27 21:55:05

标签: css

我正在使用*选择器来指示除非我另行指定,否则网站上字体的颜色应设置为某个值。

*{

font-family:"Verdana";
color: #04468e;
}

到目前为止一切顺利。问题在于,这是最常规的规则,它应该很容易被覆盖,例如

#profileMessageBoxHeader
{
background:url('images/profileMessageHeaderGradient.png') repeat-x #208ff6;
height:178px;
border-radius:10px 10px 0px 0px;
color:#fff; 
}

以下代码......

<div id="profileMessageBox">
    <div id="profileMessageBoxHeader">
        <
        <p>Please fill out the form and click submit.  Your entered profile data will be provided to the tutor, to allow them to contact you.</p>
    </div>
</div>

应该产生白色文字。但是,出于某种原因,极其通用的*规则会覆盖更具体的ID规则。为什么呢?

5 个答案:

答案 0 :(得分:3)

*是一个通用选择器,并覆盖#profileMessageBoxHeader上的设置。它与手动设置BODY,H1,P,TABLE,TR,TD,TH,PRE,UL,LI,ETC相同。有关它的更多信息以及它如何规避继承,Eric Meyer has a good article

应用以下内容,它应该有效:

#profileMessageBoxHeader p
{
    color: #FFF;
}

示例:http://jsfiddle.net/x7AnM/

答案 1 :(得分:1)

因为*正在应用于<p>。如果您将CSS更改为:

#profileMessageBoxHeader {
  background:url('images/profileMessageHeaderGradient.png') repeat-x #208ff6;
  height:178px;
  border-radius:10px 10px 0px 0px;
}

#profileMessageBoxHeader p
{
  color:#fff; 
}

......那么它应该有用。

答案 2 :(得分:1)

据我所知,元素超过id(搜索CSS权重以获取更多信息)和*指定(所有)元素,因此在规则中添加元素div,例如DIV#添加my_id

答案 3 :(得分:1)

因为“*”匹配任何元素。所以它匹配#profileMessageBoxHeader中的p标记并覆盖应用于父容器的样式(#profileMessageBoxHeader)。

如果您将样式更改为#profileMessageBoxHeader p{ color: #fff; },则会获得白色文字。或者,如果您更改标记以删除p标记,可能

<h3 id = "profileMessageBoxHeader"> Your Text </h3>

也会导致白色文字。

答案 4 :(得分:0)

我很少尝试说明你的两种风格的级联。

    <div id="profileMessageBox">
      Rule of parent
      Rule *
      <div id="profileMessageBoxHeader">
        Rule of parent
        Rule *
        Rule of #profileMessageBoxHeader
        <p>
          Rule of parent
          Rule *
        </p>
      </div>
   </div>
相关问题