Div 背景颜色在带有文档类型的视口处被截断

Div background color cuts off at viewport with doctype

我有一个带有 div 的 HTML 文档,意味着在某些文本或图像下的背景中着色(我现在在不同的网站上都有)。一个最小的案例:

<!doctype html>
<html lang="en">

<head>
  <title>Test</title>
  <meta charset="utf-8">
</head>

<body>
  <header>
    <div style="min-width: 400; background-color: black">
      <div style="font-size: x-large; color: red">
        A_Fairly_Long_Word_Or_Image
      </div>
    </div>
  </header>
</body>

</html>

我发现的问题是:如果浏览器 window(在 Firefox 47 和 IE 11 中都测试过)非常窄,然后我们向右滚动,div 背景颜色不会一直填充到文本或图像的末尾(无论是否存在最小宽度说明符)。如下图:

另一方面,如果删除 DOCTYPE 说明符,那么它实际上会按预期工作:

<html lang="en">

<head>
  <title>Test</title>
  <meta charset="utf-8">
</head>

<body>
  <header>
    <div style="min-width: 400; background-color: black">
      <div style="font-size: x-large; color: red">
        A_Fairly_Long_Word_Or_Image
      </div>
    </div>
  </header>
</body>

</html>

上面的代码在我测试时确实通过了在线验证程序。如何解决(和解释)这个问题?

乍一看,您的 min-width 声明缺少值的单位类型。

400什么?像素、百分比、ems、视口宽度?

经测试,直接调整为min-width: 400px,后台问题解决。

关于文档类型声明 (doctype),当您删除它时,浏览器会切换到怪癖模式。这使浏览器能够解析非常古老的网页——在网络标准出现之前创作的网页。

然而,以怪癖模式呈现现代网页可能是不可预测且不可靠的。虽然你现在可能会得到你想要的布局,但它并不稳定。您应该永远不要发布没有正确文档类型的网页。

更全面的解释见:

背景没有一直向右的原因是:

默认情况下,像 <div> 这样的块元素占据父级的整个宽度,假设文本示例中没有空白 space - A_Fairly_Long_Word_Or_Image,这意味着它呈现为一个单词,并且不会换行,因此文本会在较小的视口中溢出,但不会在 div.

上设置的背景溢出

然而,在怪癖模式下(没有文档类型),它的行为不同,根据这个 article:

Overflow is treated by expanding a box. When the content of an element does not fit into the dimensions specified for it (explicitly or implicitly), then overflow: visible (the default) means that the content overflows while the box dimensions are as specified. In Quirks Mode, the dimensions change; this can easily been seen e.g. if the box has a back­ground color or a border.

如何在标准模式下解决这个问题?

请使用标准 HTML5 <!doctype html> 强烈推荐。您可以将容器 div 设置为 display: inline-block; + min-width: 100%;,因为内联块的大小取决于里面的内容,最小宽度会使其扩展,即使视口是更大,查看 jsFiddle,调整输出帧的大小并查看。

.container {
  background-color: black;
  font-size: x-large;
  color: red;
  display: inline-block;
  min-width: 100%;
}
<div class="container">A_Fairly_Long_Word_Or_Image</div>

好吧,如果您确实希望文本换行,只需应用 word-break: break-all; - jsFiddle.

.container {
  background-color: black;
  font-size: x-large;
  color: red;
  word-break: break-all;
}