为什么填充会影响背景图像是否显示?

Why does padding affect whether or not a background image shows up?

我正在尝试构建一个简单的响应式设计。在这一点上,我只是在与 header 作斗争。我想在 header 中有一个背景图像,随着屏幕尺寸变大,一个不同的图像出现在它的位置。现在我只想让 iPhone 5/SE 屏幕尺寸正常工作。 HTML 有一个简单的 div:

<div class="header"></div>

并且我包括了每个人都在谈论的视口元标记:

<meta name="viewport" content="width=device-width, initial-scale=1.0">

CSS 具有以下内容:

* {
  margin: 0;
  padding: 0;
}

@media screen and (max-width: 320px) {
  .header {
    padding: 5em;
    background: url(images/header-320.png) no-repeat top left;
    background-size: contain;
  }
}

当我删除填充设置时,图像消失了。如果我将内边距设置为小于 5em,它会在图像右侧和屏幕右侧之间添加一个 space。

P.S.: 这是一个 eBay 模板,所以我需要能够在没有任何 JavaScript 的情况下做到这一点(他们不允许)。

没有padding/height

举个例子:

console.log(`Header height: ${header.clientHeight}px`);
#header {
  background-color: red;
}
<div id="header"></div>

我已经将 #header 元素设置为 background-color: red,但是你看不到任何红色,对吗?因为元素的高度默认是0px,所以元素本质上是不可见的.

和padding/height

现在看这个带填充的例子:

console.log(`Header height: ${header.clientHeight}px`);
#header {
  background-color: red;
  padding: 5em;
}
<div id="header"></div>

注意高度现在是160px,你可以看到一大堆红色。

回答你的问题

Can anyone explain this behavior, and why (it seems that) the padding setting is necessary for the image to even appear?

不需要填充。但是一个元素的高度是.

要为元素指定高度,您可以:

  • 设置height
  • 设置padding-topand/orpadding-bottom
  • 为元素(即文本,imgs)提供 HTML 内容(带高度)

If it is absolutely necessary for some reason, do I always have to set it to some arbitrary value like 5em (which I found through experimentation as opposed to any kind of logic)?

没有。阅读以上内容。

Maybe there's a clever work-around solution that I should use instead?

没有。阅读以上内容。

PS

默认情况下,具有默认值 display: block 的元素将具有默认值 width: 100%,但没有默认高度值。这就是为什么您可以看到边框宽度为 100% 但高度为 0px 的原因。

Can anyone explain this behavior, and why (it seems that) the padding setting is necessary for the image to even appear?

如@fcalderan 的评论所述,您的 div 默认情况下没有内容和样式,因此高度为零。添加内边距(或明确给它 height)时,容器将具有正高度并显示您的图像。

If it is absolutely necessary for some reason, do I always have to set it to some arbitrary value like 5em (which I found through experimentation as opposed to any kind of logic)?

这不是随意的 -- 它取决于图像的尺寸 您选择的 CSS 样式。在您的示例中,您设置了 background-size: contain,其中 "Scales the image as large as possible without cropping or stretching the image."

这最终意味着,如果您的容器按比例比背景图像宽,则它不会拉伸以适合容器,因此您必须选择与图像大小成比例的单位。在这种情况下,您的图像似乎是 320px 宽,因此设置 5em 等于 80px (5 * 16px),即 320 / 4 - 因此与图像,所以你不会看到任何空白。

如果您确实希望图像拉伸到其容器,请尝试 background-size: 100%,无论比例如何,它都应将图像拉伸到其容器。

Maybe there's a clever work-around solution that I should use instead?

无需解决方法 - 只需选择正确的 CSS 样式即可获得所需的效果。


进一步阅读: