【发布时间】:2019-01-22 16:37:41
【问题描述】:
我想选择nth child of type 并使用不同的颜色。我不想为这些元素分配 id,因为我使用模板引擎的循环生成它们。
我从这里获取了一些信息
https://www.w3schools.com/cssref/sel_first-of-type.asp
https://www.w3schools.com/cssref/sel_nth-of-type.asp
https://www.w3schools.com/cssref/sel_last-of-type.asp
这就是我得到的
#service {
background: #000000;
color: #ffffff;
border-bottom: 1px solid #424242;
}
#serviceItems {
display: flex;
margin: 0 50px;
}
.serviceItem {
flex: 1;
text-align: center;
margin-top: 0;
}
.serviceItemHeader:first-of-type {
color: #80E000;
}
.serviceItemHeader:nth-of-type(2) {
color: #F97A00;
}
.serviceItemHeader:nth-of-type(3) {
color: #B277DD;
}
.serviceItemHeader:last-of-type {
color: #e2c100;
}
<div id="service" class="section">
<div id="serviceItems">
<div class="serviceItem">
<h4 class="serviceItemHeader">Container 1</h4>
<h4>Container 1</h4>
</div>
<div class="serviceItem">
<h4 class="serviceItemHeader">Container 2</h4>
<h4>Container 2</h4>
</div>
<div class="serviceItem">
<h4 class="serviceItemHeader">Container 3</h4>
<h4>Container 3</h4>
</div>
<div class="serviceItem">
<h4 class="serviceItemHeader">Container 4</h4>
<h4>Container 4</h4>
</div>
</div>
</div>
我想知道为什么这些标题用相同的颜色着色?我希望它们有不同的颜色。
【问题讨论】:
-
直接来自您链接的源:“
:first-of-type选择器匹配其父元素的特定类型的第一个子元素。”