pistou pistou - 6 months ago 15
HTML Question

Alternate style with nth-child

I'm struggling with my styles.

I'd like to alternate the blue and green bubbles (blue > green > blue > green ...). Only the

.bubble
element should have a background-color that alternates. The
.input
should remain as is.

Here is my simplified code.



.container > div {
display: inline-block;
margin: 5px;
}

.container .bubble:nth-child(even) {
background-color: #4a94ed;
border-color: #4a64ed;
}


.container .bubble:nth-child(odd) {
background-color: #4df200;
border-color: #00f23d;
}

<div class="container">
<div class="input">input</div>
<div class="bubble">bubble 1</div>
<div class="input">input</div>
<div class="bubble">bubble 2</div>
<div class="input">input</div>
<div class="bubble">bubble 3</div>
<div class="input">input</div>
<div class="bubble">bubble 4</div>
<div class="input">input</div>
<div class="bubble">bubble 5</div>
</div>





My issue seems to come from the
.input
elements that count as an
nth-child
since only the
even
part triggers
.

Unfortunately, I can't change the HTML structure nor classes.

Do you have any idea?

Answer

Try changing your odd and even styles to:

.container .bubble:nth-child(2n) {
    background-color: #4a94ed;
    border-color: #4a64ed;
}

.container .bubble:nth-child(4n) {
    background-color: #4df200;
    border-color: #00f23d;
}

Working example: http://codepen.io/JasonGraham/pen/VjYYXd

Comments