When viewing the code below in my browser the background is white. The universal selector *
has the lowest specificity, and the body
selector comes after the universal selector. Shouldn't it be grey?
* {
background-color: white;
}
body {
background-color: grey;
}
Let's break down the code in the question:
* {
background-color: white;
}
body {
background-color: grey;
}
This is saying:
body
element and make its background color grey.Well, if the universal selector says select all elements, this would include the root element (html
).
So the code computes to:
html {
background-color: white;
}
body {
background-color: grey;
}
The root element paints the canvas white, and the body
element has no height, so the canvas remains white.
Add some content to your page or specify a height for body
and you'll see gray.
Observation made in the comments:
Interesting. But if we eliminate the
*
from the equation and just have thebody
, the page will be grey with or withoutheight
being specified. I don't quite understand why that is.
So if we eliminate the universal selector, what happens to the background-color
of the root element?
It resets to its initial value: transparent
(see: 3.2. the background-color
property)
And when the background-color
of the html
element is transparent
, the browser uses the background-color
of the body
element to paint the canvas.
3.11.2. The Canvas Background and the HTML
<body>
ElementFor documents whose root element is an HTML
HTML
element or an XHTMLhtml
element: if the computed value ofbackground-image
on the root element isnone
and itsbackground-color
istransparent
, user agents must instead propagate the computed values of the background properties from that element's first HTMLBODY
or XHTMLbody
child element. The used values of thatBODY
element's background properties are their initial values, and the propagated values are treated as if they were specified on the root element. It is recommended that authors of HTML documents specify the canvas background for theBODY
element rather than theHTML
element.