<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
font-size: 16px;
width: 70vw;
height: 40vh;
background-color: yellow;
}
h1 {
background-color: red;
}
</style>
</head>
<body>
<h1>My First Heading</h1>
</body>
</html>
在上面的代码中,我将 width
设置为 70vw
,将 height
设置为 40vh
。
我有两个问题:
- 为什么
html,body
的 height
仍然填满视口(viewport)高度的 100%,而我使用 40vh 指定它应该只填满 40%
在 html,body
声明中?
- 为什么 h1 元素的宽度设置为
html,body
声明中的 70vw
,即使宽度不是继承的,但 h1 的高度未设置为40vh
来自 html,body
声明?
其实是可以的,但是css有一个tricky的地方。 html
获取 body
的背景,如果它在 html
本身上未设置并且视口(viewport)由 html 的背景填充(这是 css 中子项的唯一继承).
此行为在 CSS Backgrounds and Borders Module Level 3 中指定:
The document canvas is the infinite surface over which the document is rendered. [CSS2] Since no element corresponds to the canvas, in order to allow styling of the canvas CSS propagates the background of the root element
For documents whose root element is an HTML HTML element or an XHTML html element [HTML]: if the computed value of background-image on the root element is none and its background-color is transparent, user agents must instead propagate the computed values of the background properties from that element’s first HTML BODY or XHTML body child element.
我已经在你的示例中添加了 html
的背景,你可以看到,没问题:
html, body {
font-size: 16px;
width: 70vw;
height: 40vh;
background-color: yellow;
}
html {
background: white;
}
h1 {
background-color: red;
}
<h1>My First Heading</h1>
我能做的另一件事是概述 - 它会显示元素实际结束的位置:
html, body {
font-size: 16px;
width: 70vw;
height: 40vh;
background-color: yellow;
outline: 1px dotted blue;
outline-offset: -1px;
}
h1 {
background-color: red;
}
<h1>My First Heading</h1>
另一个有趣的案例:
html {
width: 50vw;
height: 50vh;
}
body {
margin: 40vh 0 0 40vw;
width: 30vw;
height: 30vh;
background: linear-gradient(45deg, red, blue);
}
html, body {
border: 8px solid;
}