我想改变替代元素的颜色,但我的代码不起作用。我的代码更改了整个容器元素的颜色。
任何人都可以告诉我,我在代码中哪里出错了吗?
.pvt-msg-panel {
height: 92vh;
float: left;
margin-top: -20px;
}
#pvt-messages-box {
height: 50vh;
width: 650px;
margin-top: 10px;
margin-left: 10px;
overflow-y: scroll;
}
.pvt-messages-box-item {
padding: 10px;
padding-left: 20px;
position: relative;
display: inline-block;
width: 100%;
color: black;
padding-left: 20px;
font-size: 12px;
cursor: pointer;
}
.pvt-messages-box-item:nth-child(odd) {
background-color: green;
}
.pvt-messages-box-item:nth-child(even) {
background-color: white;
}
<div class="pvt-msg-panel">
<section id="pvt-messages-box">
<span class="pvt-messages-box-item"><span><img src="images/avatar2.png"></span>message 1</span>
<br>
<span class="pvt-messages-box-item"><span><img src="images/avatar2.png"></span>message 2</span>
<br>
<span class="pvt-messages-box-item"><span><img src="images/avatar2.png"></span>message 3</span>
<br>
</section>
</div>
答案 0 :(得分:8)
使用first-child
选择器时,br
代码会尝试选择even
选择器。尝试使用nth-of-type
选择器,然后去:
.pvt-msg-panel{
height: 92vh;
float: left;
margin-top: -20px;
}
#pvt-messages-box{
height: 50vh;
width: 650px;
margin-top: 10px;
margin-left: 10px;
overflow-y: scroll;
}
.pvt-messages-box-item{
padding:10px;
padding-left: 20px;
position: relative;
display: inline-block;
width: 100%;
color: black;
padding-left: 20px;
font-size: 12px;
cursor: pointer;
}
.pvt-messages-box-item:nth-of-type(odd){
background-color: green;
}
.pvt-messages-box-item:nth-of-type(even){
background-color: white;
}
&#13;
<div class="pvt-msg-panel">
<section id="pvt-messages-box">
<span class="pvt-messages-box-item"><span><img src="images/avatar2.png"></span>message 1</span><br>
<span class="pvt-messages-box-item"><span><img src="images/avatar2.png"></span>message 2</span><br>
<span class="pvt-messages-box-item"><span><img src="images/avatar2.png"></span>message 3</span><br>
</section>
</div>
&#13;
答案 1 :(得分:3)
这里有jsfiddle。将nth-of-type(odd)
用于span
.pvt-messages-box-item:nth-of-type(odd){
background-color: green;
}
.pvt-messages-box-item:nth-of-type(even){
background-color: white;
}
:如果元素是其父元素的指定子元素,则第n个子元素匹配。 div中的
元素会导致选择器的奇数和偶数部分失败,因为它会使两个跨越奇数子(第1和第3个)的父级。
答案 2 :(得分:2)