Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

.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>
like image 531
Krisalay Avatar asked Aug 20 '16 09:08

Krisalay


1 Answers

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:

.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>
like image 134
kukkuz Avatar answered Sep 28 '22 01:09

kukkuz