Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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?

like image 412
Drazzah Avatar asked Dec 17 '14 16:12

Drazzah


People also ask

How do I add background color to margin?

Margin is creating space beyond the box model elements. So, we cannot apply color to the margin. If our requirement still applies color around the elements, instead of margin you can use padding. The padding property in html gives space around the innermost element's content of the box-like structure.

Does background color affect margin?

The simple answer is the padding area and the content area. Let's confirm this by using an example. From the example above, we can see that the margin area and the border area are not affected by the change in background color.

Can we give color to margin?

you can't color a margin, but the element exposed on either side is the body – you can set the background-color of that (it's in the style tags in the head of your html doc).

What is the background color of a margin area?

Margins don't have a color. They just push elements apart. You could use a wide border instead, or you can have a background color showing in the padding area. The margin colour will be whatever colour is assigned to the container that the elements are in.


1 Answers

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>
like image 79
vals Avatar answered Nov 25 '22 13:11

vals