Lets say we have this layout:
<div id="container">
<div></div>
<div></div>
<div class="current"></div>
<div></div>
<div></div>
</div>
With some CSS:
#container div {
width: 20px;
height: 20px;
}
How can I make all divs before and including the div (within #container
) with class current
have the same background colour e.g. background: tomato;
? And update if the div that the class="current"
is on changes?
So in the example above the first 3 divs within the container would have a background colour of tomato.
You can use the general sibling selector.
#container div {
width: 20px;
height: 20px;
background-color:tomato;
}
#container .current ~ div {
background-color:transparent;
}
<div id="container">
<div>1</div>
<div>2</div>
<div class="current">3</div>
<div>4</div>
<div>5</div>
</div>
here is a different way of working it out
http://jsfiddle.net/27LjLqm2/
<div id="container">
<div>1</div>
<div>2</div>
<div class="current">3</div>
<div>4</div>
<div>5</div>
</div>
#container div {
width: 20px;
height: 20px;
background:tomato;
}
#container div:nth-last-child(-n+2){
background:transparent;
}
we are targeting the last DIV of the list
" -n " being beneath the 5th div so the +2 will make us go to the top twice.
using "+1" would make "div 5" background transparent.
+2 would go all the way from "div 5 to div 4" and make their background transparent.
you can play a bit with it by using +3 then +4 to see what gets changed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With