为什么身体背景颜色不起作用?

时间:2016-01-09 20:00:10

标签: html css css-selectors css-specificity

在浏览器中查看下面的代码时,背景为白色。通用选择器*具有lowest specificitybody选择器位于通用选择器之后。它不应该是灰色的吗?

* {
    background-color: white;
}

body {
    background-color: grey;
}

4 个答案:

答案 0 :(得分:5)

让我们分解问题中的代码:

* {
    background-color: white;
}

body {
    background-color: grey;
}

这就是说:

  1. 选择每个元素并使其背景颜色为白色。
  2. 选择body元素并将其背景颜色设置为灰色。
  3. 好吧,如果universal selector选择所有元素,则会包含根元素(html)。

    因此代码计算为:

    html {
        background-color: white;
    }
    
    body {
        background-color: grey;
    }
    

    根元素将画布描绘为白色,body元素没有高度,因此画布保持白色。

    在页面中添加一些内容或指定body的高度,然后您就会看到灰色。

    评论中的观察:

      

    有趣。但是,如果我们从等式中删除*并且只有body,则无论是否指定height,页面都将为灰色。我不太明白为什么会这样。

    因此,如果我们消除了通用选择器,那么根元素的background-color会发生什么?

    重置为初始值:transparent(请参阅:3.2. the background-color property

    background-color元素的htmltransparent时,浏览器使用background-color元素的body绘制画布

      

    3.11.2. The Canvas Background and the HTML <body> Element

         

    对于其根元素是HTML HTML元素或XHTML的文档   html元素:如果background-image的计算值为   根元素为none,其background-colortransparent,   用户代理必须传播计算的值   该元素的第一个HTML BODY或XHTML的背景属性   body子元素。 BODY元素的使用值   background属性是它们的初始值,并且是传播的   将值视为在根元素上指定的值。它   建议HTML文档的作者指定画布   BODY元素的背景而不是HTML元素。

答案 1 :(得分:1)

您的body元素可能为空(或仅包含其他元素,但不包含直接文本)。

body添加一些文字。你会看到它的背景是灰色的。

您的* {background-color: white;}html元素和任何其他元素(body除外)提供了白色背景。因此,如果您的body仅包含div元素,则此div将具有白色背景,并且您将看不到灰色的body背景,因为div完全填写它。如果您将body提供给padding,则会看到背景颜色。

    * {
        background-color: white;
    }

    body {
        background-color: grey;
        padding:1%;
    }

答案 2 :(得分:0)

我认为身体的背景会发生更改,但由于身体内的孩子受*选择器的影响,您实际上无法看到它。 *还会选择身体的子项,并设置这些元素的背景,覆盖身体的背景。

* { background-color: white }
body { background-color: grey }
<p>Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text</p>

<p>相对的相同片段相对于显示正文的background-color

* { background-color: white }
body { background-color: grey }
p {
  position: relative;
  top: 50px;
}
<p>Text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text text</p>

此外,如果你的身体是空的,那么t就没有高度,因此它基本上是不可见的。

答案 3 :(得分:0)

*选择所有元素和此代码

* {
    background-color: white;
}

将每个元素的背景颜色更改为白色。然后将体背景颜色覆盖为灰色,因为元素选择器“body”比*

更具体
body {
    background-color: grey;
}

你没有看到它,因为你体内没有任何内容。 在这里,您可以看到css selectors以及如何Calculating a selector's specificity