Html CSS:仅在边距内的背景颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10048800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:38:11  来源:igfitidea点击:

CSS: background-color only inside the margin

htmlcssmarginbackground-color

提问by Erik Funkenbusch

I have searched for an answer but couldn't find it anywhere. My question is reasonably simple: I have a background color of my body, then a large margin, and now I want a different background color insidethe margin.

我已经搜索了答案,但在任何地方都找不到。我的问题相当简单:我的身体有一个背景颜色,然后是一个很大的边距,现在我想要一个不同的背景颜色边距内。

How do I do that with CSS?

我如何用 CSS 做到这一点?

回答by Erik Funkenbusch

If your margin is set on the body, then setting the background color of the html tag should color the margin area

如果您的边距设置在正文上,则设置 html 标签的背景颜色应为边距区域着色

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

或者作为 dmackerman 的建议,将边距设置为 0,但是设置一个你想要的边距大小的边框并设置边框颜色

回答by dmackerman

Instead of using a margin, could you use a border? You should do this with <div>, anyway.

除了使用边距,您可以使用边框吗?<div>无论如何,您应该使用 来执行此操作。

Something like this?enter image description here

像这样的东西?在此处输入图片说明

http://jsfiddle.net/GBTHv/

http://jsfiddle.net/GBTHv/

回答by rlv-dan

I needed something similar, and came up with using the :before (or :after) pseudoclasses:

我需要类似的东西,并想出了使用 :before (或 :after) 伪类:

#mydiv {
   background-color: #fbb;
   margin-top: 100px;
   position: relative;
}
#mydiv:before {
   content: "";
   background-color: #bfb;
   top: -100px;
   height: 100px;
   width: 100%;
   position: absolute;
}

JSFiddle

JSFiddle

回答by worenga

That is not possible du to the Box Model. However you could use a workaround with css3's border-image, or border-color in general css.

由于盒模型,这是不可能的。但是,您可以使用 css3 的边框图像或一般 css 中的边框颜色的解决方法。

However im unsure whether you may have a problem with resetting. Some browsers do set a margin to html as well. See Eric Meyers Reset CSS for more!

但是我不确定您是否在重置时遇到问题。一些浏览器也为 html 设置了边距。参见 Eric Meyers 重置 CSS 了解更多!

html{margin:0;padding:0;}