【问题标题】:Why does the height on html element not have effect? [duplicate]为什么html元素的高度不起作用? [复制]
【发布时间】:2017-12-27 21:09:26
【问题描述】:

<!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,body 声明中使用40vh 指定它应该只填充40% 时,html,bodyheight 仍然填充100% 的视口高度?
  2. 为什么 h1 元素的宽度从 html,body 声明中设置为 70vw,即使宽度没有被继承但 h1 的高度未从 html,body 声明中设置为 40vh?李>

【问题讨论】:

  • 对于第二个问题.. h1 是块元素 si 它需要 100% 的容器宽度和高度是自动的,所以它取决于内容而不是父的高度
  • 对于第一个问题,在 html,body 的声明中添加边框,您会看到它采用了您指定的高度/宽度
  • 那么问题是为什么背景颜色会应用在它之外?
  • 这就是我评论的原因,我还不知道背景:)
  • @TemaniAfif 但是元素的宽度取决于父元素的宽度,对吧?因为每当我将html,body 上的width 更改为例如width:50vhwidth:60vh 等时,h1 的红色背景都会相应更改。

标签: html css


【解决方案1】:

它确实有效,但在 css 中有一个棘手的地方。 html 获取 body 的背景,如果它在 html 本身上未设置并且视口由 html 的背景填充(这是 css 中唯一从子级继承的)。

此行为在CSS Backgrounds and Borders Module Level 3 中指定:

文档画布是呈现文档的无限表面。 [CSS2] 由于没有元素对应于画布,因此为了允许画布的样式 CSS 传播根元素的背景

对于根元素是 HTML HTML 元素或 XHTML html 元素 [HTML] 的文档:如果根元素上的 background-image 的计算值为 none 并且其 background-color 是透明的,则用户代理必须改为传播从该元素的第一个 HTML BODY 或 XHTML 主体子元素计算出的背景属性值。

我在您的示例中添加了html 的背景,您可以看到,这很好:

html, body {
  font-size: 16px;
  width: 70vw;
  height: 40vh;
  background-color: yellow;
}

html {
  background: white;
}

h1 {
  background-color: red;
}
&lt;h1&gt;My First Heading&lt;/h1&gt;

我可以做的另一件事是大纲 - 它会显示元素实际结束的位置:

html, body {
  font-size: 16px;
  width: 70vw;
  height: 40vh;
  background-color: yellow;
  outline: 1px dotted blue;
  outline-offset: -1px;
}

h1 {
  background-color: red;
}
&lt;h1&gt;My First Heading&lt;/h1&gt;

另一个有趣的案例:

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 会获取正文的背景 我可以在哪里阅读?
  • @TemaniAfif,更新了答案。
  • 只设置body 元素的样式而不设置html 元素的样式更好吗?
  • @ToothyRel,我也没有。
【解决方案2】:

你看到整个背景都是黄色的原因是因为

根元素的背景成为画布的背景并覆盖整个画布[...]

尝试给身体赋予不同的颜色,你会发现不同

<!DOCTYPE html>
<html>

<head>
  <style>
    html,
    body {
      font-size: 16px;
      width: 70vw;
      height: 40vh;
      background-color: yellow;
    }
    
    h1 {
      background-color: red;
    }
  </style>
</head>

<body style="background-color:blue;">
  <h1>My First Heading</h1>
</body>

</html>

Read here in details

【讨论】:

  • 即使你从 HTML 中删除背景我们也看到了,你只能保留正文中的一个
  • @TemaniAfif,不。
  • 也删除 html 之一:)
  • 是的,这也是我的意思;)因为它不仅是关于 HTML 的背景,还有关于正文的背景转到 HTML 的技巧
猜你喜欢
  • 2011-08-05
  • 1970-01-01
  • 2019-12-24
  • 1970-01-01
  • 2021-09-05
  • 2011-10-06
  • 2020-09-23
  • 2015-01-06
相关资源
最近更新 更多