为什么 <!DOCTYPE html> 会更改页面布局?

Why is <!DOCTYPE html> changing page layout?

我正在写一个带有背景图片的网页。这是 CSS:

body {
    image-rendering: pixelated;
    background-image: url("Images/page-background.png");
    background-size: 100% 100%;
}

效果不错;该图像与页面具有相同的尺寸。然后我意识到我忘记在 html 的顶部包含 <!DOCTYPE html>,所以我添加了,因为我认为它不会改变任何东西。当我再次加载页面时,背景图像在页面各处重复出现。任何人都可以解释为什么会发生这种情况,以及我可以做些什么来解决它?再次删除 <!DOCTYPE html> 真的可以吗,还是有办法修复它?

即使您有 <!DOCTYPE>(我建议您 do include,这也会让您以浏览器的全尺寸显示单个图像,因为这是更好的做法):

html, body {
  width: 100%; height: 100%;
  margin: 0; padding: 0;
}
body {
    image-rendering: pixelated;
    background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Square_definition.svg/178px-Square_definition.svg.png");
    background-size: contain;
    background-position: center;
    background-repeat: no-repeat;
}

请注意,务必确保 htmlbody 元素的大小为 100%(并删除浏览器添加的任何默认边距 + 填充)。

注意我使用了随机示例图像。

编辑:D.Pardal 正确地指出这个答案并不能解释观察到的差异。

大部分解释来自以下事实:

  • 添加 <!DOCTYPE html> 将文档放入 "standards mode"
  • "Standards mode" 指示 body 元素的高度默认为包含其内容所需的最小尺寸

没有<!DOCTYPE html>的原始版本有一个<body>填满了页面。将背景图像应用于此 <body>background-size: 100% 100% 会填满整个页面。添加 DOCTYPE 会缩小 body 的高度。

"Why is the image visible at all if its height is equal to the <body>'s height of 0?"

因为 body 有默认边距,由浏览器应用,这些都计入背景图像的高度。

"Why wasn't the image repeating in the first place?"

重复了!然而,第一次重复足够大,可以填满整个父级。这可以通过删除 DOCTYPE 并将图像的大小缩小到 background-size: 20% 20%;.

来验证

正如我在此处解释的那样: 在设置 bacground-size:100% 100% 添加了文档类型时,您面临着复杂的背景传播:

body {
    image-rendering: pixelated;
    background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Square_definition.svg/178px-Square_definition.svg.png");
    background-size: 100% 100%;
    background-position: center;
}

渐变颜色也会发生同样的情况,因为默认情况下渐变的大小为 100% 100%

body {
    image-rendering: pixelated;
    background-image:linear-gradient(to bottom,red,blue);
}


要解决您的问题,您只需确保 html 元素至少为 height:100%

html {
  min-height:100%;
}

body {
    image-rendering: pixelated;
    background-image: url("https://upload.wikimedia.org/wikipedia/commons/thumb/2/2f/Square_definition.svg/178px-Square_definition.svg.png");
    background-size: 100% 100%;
    background-position: center;
}


如果你删除文档类型将落入 并且行为会有所不同,但你不应该真正关心这个,因为你 必须 将文档类型添加到你的文档: