Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select every two elements alternating?

I would like to select every two rows and alternate and repeat in that pattern. How can I do this using CSS?

For example....

Blue Rows: 1,2,5,6,9,10

Red Rows: 3,4,7,8

ul{
  list-style-type: none;
  color: white;
}
li:nth-of-type(odd){
  background-color:blue;
}
li:nth-of-type(even){
  background-color:red;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul

EDIT: I forgot to add a key point, sorry! This repetition will be used in an ng-repeat of unknown length so it could go on forever. So i won't be able to explicity type by every 2 in the css.

like image 818
big_water Avatar asked Mar 08 '23 07:03

big_water


1 Answers

The logical rules for doing this are the following.

  • Select every fourth, and the next one. Color that in red.
  • Select every fourth and then move two ahead, and the next one. Color that in blue.

"Move to the next one" can be done by using the + combinator (next sibling).

ul{
  list-style-type: none;
  color: white;
}
li:nth-of-type(4n+3), li:nth-of-type(4n+3) + * {
  background-color:blue;
}
li:nth-of-type(4n+1), li:nth-of-type(4n+1) + * {
  background-color:red;
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
</ul

Or, as Hamms suggested in the comments section below, you can use 4n+1 and 4n+2 for blue; and 4n+3 and 4n for red.

like image 73
Lazar Ljubenović Avatar answered Mar 30 '23 17:03

Lazar Ljubenović