Can I set a background-color to margins and padding?

css
10,211

Solution 1

It's not possible to set the background-colors of the padding and margin attributes. They are meant to be transparent, or invisible, and used solely for positioning purposes.

However, I have heard this question many times, and I completely understand wanting to show the padding and margins for purely educational purposes. Therefore, I have created a simple little "hack" to represent the box-model, using CSS's :before and :after psuedo-elements.

You can't color padding, or margins, but let me suggest a little hack to make it look like you can (without JavaScript!):

simulated box-model:

#box {
  width: 150px;
  height: 150px;
  background: green;
  position: relative;
  border: 10px solid blue;
  left: 50px;
  top: 50px;
}
#box:before {
  background: red;
  content: 'border';
  display: block;
  position: absolute;
  top: -30px;
  left: -30px;
  right: -30px;
  bottom: -30px;
  z-index: -1;
}
#box:after {
  background: gray;
  content: 'margin';
  display: block;
  position: absolute;
  top: -50px;
  left: -50px;
  right: -50px;
  bottom: -50px;
  z-index: -2;
}
<div id="box">#box</div>

Solution 2

The property that you are looking for is background-clip

div {
    width: 100px;
    height: 100px;
    padding: 30px;
    border: 30px solid transparent;
    background-color: blue;
}
.test1 {background-clip: content-box;}
.test2 {background-clip: padding-box;}
.test3 {background-clip: border-box;}
<div class="test1"></div>
<div class="test2"></div>
<div class="test3"></div>

And another solution, combining both in a single div

div {
    width: 100px;
    height: 100px;
    padding: 30px;
    border: 30px solid transparent;
    background-image: linear-gradient(0deg, yellow, yellow), 
                      linear-gradient(0deg, green, green), 
                      linear-gradient(0deg, blue, blue);
    background-clip: content-box, padding-box, border-box;
}
<div></div>
Share:
10,211

Related videos on Youtube

Drazzah
Author by

Drazzah

I specialize in CSS, JS and HTML. I've learned a lot from StackOverflow.com, and I'm glad to be a part of it. Thank you all for your help!

Updated on September 16, 2022

Comments

  • Drazzah
    Drazzah over 1 year

    I want to color the margins and padding of a <div> so that I can use it educationally to represent the box-model in CSS. How can I set a color for those elements?