html - 为什么html元素的高度没有效果?

标签 html css

<分区>

<!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

我有两个问题:

  1. 为什么 html,bodyheight 仍然填满视口(viewport)高度的 100%,而我使用 40vh 指定它应该只填满 40% html,body 声明中?
  2. 为什么 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;
}

关于html - 为什么html元素的高度没有效果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47998676/

相关文章:

html - 如何从原始 HTML 代码制作 CSS 菜单

html - 具有折叠 Angular 效果和动画的 CSS 按钮

html - Bootstrap 列宽 - 删除其他容器时自动调整大小

html - 个别 Div 的个别背景图片

css - div 的水平居中可以通过 margin-left 和 right auto 以及宽度或最大宽度来完成,但不是最小宽度?

html - HTML 文件 : how to separate CSS rules when classes and id's can be the same? 中有多个 "HTML"标签

html - 是否有可能使 float DIV 在不适合容器时不换行?

javascript - 每秒动态更改背景图像

jquery - CSS 替代此 CSS-jQuery 代码?

html - 防止嵌套内容被周围的css格式化