[英]Is there a way to have the equivalent of multiple :before and :after pseudo-elements in CSS?
目前我有这个标记代表一个图标容器和一些用CSS设置的元素,最后显示为图形图标。
<div class="icon">
<div class="icon-element1"></div>
<div class="icon-element2"></div>
<div class="icon-element3"></div>
</div>
根据图标的复杂程度,子元素的数量可以不同。
我想要的是以某种方式尽可能多地移动到CSS样式表,所以理想情况下我只有<div class="icon"></div>
,其余的只是从CSS样式渲染,在概念上接近:before/:after
,一种虚拟的div。 我不想使用JavaScript动态添加元素。 如果我们有多个:before/:after
可以这样做。
以下是使用上面的标记获得的图标示例:
如您所见,有3个子元素代表灰色表壳,白色屏幕和绿松石按钮。
请告知,我如何简化这个标记,以便每次我想要显示这个图标时都不必放置所有div。
你可以使用nth-child()
。
.icon:nth-child(2) {
color:red;
}
在这种情况下,选择器将有效地为.icon
的第二个子项设置.icon
。
您不需要冗余的.icon-element
类。
我知道您说子元素的数量会有所不同,但是,除了缩减标记之外,此方法与您当前使用的方法之间没有区别 - 这正是您想要的。
此外,还有相邻的兄弟选择器+
也可以有效地使用。
你可以使用::before
和::after
实际实现图像中的图标,如果你在<div class="icon">
上设置position:relative
,并绝对定位伪元素:
.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
不会削减它。
如果您的图标仅由平面颜色(或渐变)区域组成,则多个渐变背景可能适用于具有更多元素的图标:
.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;
}
你甚至可以使用一个渐变背景做同样的事情,使用锐利的渐变边界:
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
它们的样式,可能会产生更清晰的代码,如其他地方所建议的那样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.