如果您在<div class="icon"> 上设置position:relative,并且绝对定位伪元素,您实际上可以只使用::before 和::after 来实现图像中的图标:
http://jsfiddle.net/RMs2L/3/
.icon {
position: relative;
width: 160px;
height: 160px;
background: #666;
}
.icon::before,
.icon::after {
content: '';
position: absolute;
width: 120px;
left: 20px;
}
.icon::before {
height: 80px;
top: 20px;
background: #fff;
}
.icon::after {
height: 20px;
bottom: 20px;
background: #00b9ae;
}
(未在 IE 中测试。)
但你说得对,对于超过三个部分的图标,::before 和 ::after 不会削减它。
如果您的图标仅由纯色(或渐变)区域组成,那么多个渐变背景可能适用于具有更多元素的图标:
http://jsfiddle.net/RMs2L/5/
.icon {
position: relative;
width: 160px;
height: 160px;
background-color: #666;
background-image: linear-gradient(to bottom, #fff 0%, #fff 100%)
, linear-gradient(to bottom, #00b9ae 0%, #00b9ae 100%)
, linear-gradient(to bottom, #000 0%, #000 100%);
background-size: 120px 40px
, 120px 20px
, 120px 20px;
background-position: 20px 20px
, 20px 80px
, 20px 120px;
background-repeat: no-repeat;
}
你甚至可以用一个渐变背景做同样的事情,使用锐利的渐变边界:
http://jsfiddle.net/RMs2L/6/
background-image: linear-gradient(to bottom,
#fff 0px, #fff 40px,
rgba(0,0,0,0) 40px, rgba(0,0,0,0) 60px,
#00b9ae 60px, #00b9ae 80px,
rgba(0,0,0,0) 80px, rgba(0,0,0,0) 100px,
#000 100px, #000 120px);
background-size: 120px 120px;
background-position: 20px 20px;
当然,您可以使用实际的背景图像文件以及渐变或代替渐变。
如您所见,如果您尝试使用渐变背景制作图标,那么 CSS 会比设置实际元素或伪元素的样式要复杂得多。如果您将其吸收并放入 HTML 元素,并按照其他地方的建议使用:nth-child 设置它们的样式,它可能会使代码更清晰。