Can I set the background color for margins and indents?

I want to color the margins and indents <div>so that I can use it in the curriculum to represent the box-model in CSS. How to set color for these elements?

+4
source share
2 answers

Unable to set background-colorpadding attributes and fields. They must be transparent or invisible and used exclusively for positioning purposes.

Nevertheless, I have heard this question many times, and I fully understand that I want to show additions and fields for purely educational purposes. So I created a simple little hack to represent box-model using CSS :beforeand :afterpsuedo-elements.

You cannot type color or fields, but let me suggest a little hack to make it look the way 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>
Run code
+3
source

The property 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>
Run code

And another solution combining both in one 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>
Run code
+2
source

Source: https://habr.com/ru/post/1568017/


All Articles