我想为<div>
的边距和填充着色,以便我可以在教育上用它来表示CSS中的盒子模型。如何为这些元素设置颜色?
答案 0 :(得分:3)
无法设置填充和边距属性的background-color
。它们应该是透明的或不可见的,仅用于定位目的。
但是,我多次听过这个问题,而且我完全理解为了纯粹的教育目的而想要显示填充和边距。因此,我创建了一个简单的小“hack”来表示框模型,使用CSS的:before
和:after
伪元素。
你不能对填充或边距进行颜色处理,但是让我建议一点点破解让它看起来像你可以(没有JavaScript!):
#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>
答案 1 :(得分:2)
您正在寻找的属性是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>
另一种解决方案,将两者结合在一起
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>