【问题标题】:How to prevent background color of a body tag from spilling onto it's margin如何防止正文标签的背景颜色溢出到其边缘
【发布时间】:2013-06-19 22:16:43
【问题描述】:

我正在编写一个非常简单的 css 代码,如下所示:

body {
background-color:#616161;
margin-left: 20%;
}

即使我在左侧指定了 20% 的边距,背景颜色也会影响 body 标签的边距区域。如何确保背景颜色保持在边框内?

【问题讨论】:

标签: css margin background-color


【解决方案1】:

使用 div 放入背景色

<html>
<body>
<div class="background">
<p>This is some text</p>
</div>
</body>
</html>

然后使用这个 CSS 来分配颜色和边距,你必须调整代码以获得你想要的宽度和高度

html{
height:100%;
}
body{
height:100%;
margin-top:0px;
margin-left: 20%;
}
.background{
min-height:100%;
height:auto;
background-color:#616161;
width:100%;
}

或者正如米罗指出的那样:

html { background-color:#fff; }
body {
background-color:#616161;
margin:0% 0% 0% 20%;
}

【讨论】:

    【解决方案2】:

    找到了对该浏览器行为的很好描述:“body 元素上的背景属性将传播到 html 元素(视口),但前提是后者为背景属性计算的值是透明的。” (link) + (testing fiddle)。

    这里最好的解决方案是使用额外的div,就像上面建议的user2067005
    W3C 建议:

    但是,对于 HTML 文档,我们建议作者指定 BODY 元素而不是 HTML 元素的背景。 对于根元素是 HTML“HTML”元素或 XHTML“html”的文档" 元素的 'background-color' 计算值为 'transparent','background-image' 计算值为 'none',用户代理必须使用该元素的第一个 HTML“BODY”元素或 XHTML 的背景属性的计算值为画布绘制背景时的“body”元素子元素,并且不得为该子元素绘制背景。这样的背景也必须锚定在同一点,就像它们只为根元素绘制时一样。 (link)

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2014-12-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多