Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply CSS to all divs in a container before current div only

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.

like image 956
wadclapp Avatar asked Nov 21 '15 20:11

wadclapp


2 Answers

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>
like image 144
Marcelo Avatar answered Sep 28 '22 01:09

Marcelo


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

like image 44
Gad Avatar answered Sep 27 '22 23:09

Gad