Krisalay Krisalay - 3 months ago 14
CSS Question

change the background-color of alternate elements css

I wanna change the color of alternate elements, but my code is not working. My code changes the color of the whole container element. can anyone please tell me where am i making mistake in the code?

<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>

.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;
}

Answer

When using first-child selector, the br tags will try to pick up the even selector. Try using the nth-of-type selector and there you go!

Check this out and let me know your feedback. Thanks!

.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;
}
<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>