将CSS应用到html,body和*有什么区别? [英] What's the difference in applying CSS to html, body, and *?

查看:92
本文介绍了将CSS应用到html,body和*有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这三个规则在应用到同一个HTML文档时有什么不同?

How are these three rules different when applied to the same HTML document?

html {
    color: black;
    background-color: white;
}

body {
    color: black;
    background-color: white;
}

* {
    color: black;
    background-color: white;
}


推荐答案




html {
    color: black;
    background-color: white;
}

此规则将颜色应用于 html 元素。 html 元素的所有后代继承其颜色(但不是 background-color ),包括 body body 元素没有默认背景颜色,这意味着它是透明的,因此 html 的背景将显示直到和除非你为 body 设置了一个背景。

This rule applies the colors to the html element. All descendants of the html element inherit its color (but not background-color), including body. The body element has no default background color, meaning it's transparent, so html's background will show through until and unless you set a background for body.

虽然 html 绘制在整个视口上, html 元素本身不会自动跨越视口的整个高度;背景只是传播到视口。有关详情,请参阅此答案

Although the background of html is painted over the entire viewport, the html element itself does not span the entire height of the viewport automatically; the background is simply propagated to the viewport. See this answer for details.

body {
    color: black;
    background-color: white;
}

此规则将颜色应用于 code>元素。 body 元素的所有后代继承其颜色

This rule applies the colors to the body element. All descendants of the body element inherit its color.

类似于 html 的背景如何自动传播到视口, body 的背景将被传播到 html ,除非您为 html 设置了背景。有关说明,请参见此答案。因此,如果你只需要一个背景(在通常情况下),无论你使用第一条规则还是第二条规则都不会产生任何真正的区别。

Similarly to how the background of html is propagated to the viewport automatically, the background of body will be propagated to html automatically, until and unless you set a background for html as well. See this answer for an explanation. Because of this, if you only need one background (in usual circumstances), whether you use the first rule or the second rule won't make any real difference.

可以组合 html body 的背景样式与其他技巧,以获得一些漂亮的背景效果,如我在这里。请参阅上面的链接答案。

You can, however, combine background styles for html and body with other tricks to get some nifty background effects, like I've done here. See the above linked answer for how.

* {
    color: black;
    background-color: white;
}

此规则将颜色应用于每个元素因此这两个属性都不会被隐式继承。但是你可以很容易地用任何其他的方法重写这个规则,包括上面两个规则,因为 * 在选择器特性上没有意义。

This rule applies the colors to every element, so neither of the two properties is implicitly inherited. But you can easily override this rule with anything else, including either of the above two rules, as * has literally no significance in selector specificity.

这篇关于将CSS应用到html,body和*有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆