CSS: background-color only inside the margin

HtmlCssMarginBackground Color

Html Problem Overview


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 inside the margin.

How do I do that with CSS?

Html Solutions


Solution 1 - Html

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

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

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

Solution 2 - Html

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

Something like this?enter image description here

http://jsfiddle.net/GBTHv/

Solution 3 - Html

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

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

JSFiddle

Solution 4 - Html

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.

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{margin:0;padding:0;}

Solution 5 - Html

Are you possibly looking to change the margin color outside the border? Maybe https://www.w3schools.com/css/css_outline.asp[outline][1] outline will help? Particularly

outline-color: green;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1318194View Question on Stackoverflow
Solution 1 - HtmlErik FunkenbuschView Answer on Stackoverflow
Solution 2 - HtmldmackermanView Answer on Stackoverflow
Solution 3 - Htmlrlv-danView Answer on Stackoverflow
Solution 4 - HtmlworengaView Answer on Stackoverflow
Solution 5 - HtmlKatherine LangleyView Answer on Stackoverflow