Alternating Bullet List Colours

Viewed 79

Does anyone know if it's possible to dynamically alternate the colour of an unordered list bullet for all lists on a site?

For example the first bullet in the list is green, second bullet is blue and the third bullet is orange and so on.

I've tried to use JQuery here, but it's impossible to target the :before pseudoelement.

<p> Shopping List </p>
<ul>
  <li>Jalapeños</li>
  <li>Milk</li>
  <li>Eggs</li>
</ul>

3 Answers

Consider the following CSS Styling.

ul.colored {
  list-style: none;
}

ul.colored li.blue-bullet::before {
  content: "\2022";
  color: blue;
  font-weight: bold;
  display: inline-block;
  width: 1em;
  margin-left: -1em;
}

ul.colored li.orange-bullet::before {
  content: "\2022";
  color: orange;
  font-weight: bold;
  display: inline-block;
  width: 1em;
  margin-left: -1em;
}

ul.colored li.green-bullet::before {
  content: "\2022";
  color: green;
  font-weight: bold;
  display: inline-block;
  width: 1em;
  margin-left: -1em;
}
<p> Shopping List </p>
<ul class="colored">
  <li class="blue-bullet">Jalapeños</li>
  <li class="green-bullet">Milk</li>
  <li class="orange-bullet">Eggs</li>
</ul>

If you want to do this with JS/jQuery, you could make new bullets within a Span and style it that way too.

Ref: https://www.w3schools.com/howto/howto_css_bullet_color.asp

use li:nth-of-type(3n+x)::before like this

ul {
  list-style: none;
}

ul li::before {
  content: "\2022";
  color: red;
  font-weight: bold;
  display: inline-block; 
  width: 1em;
  margin-left: -1em;
}

ul li:nth-of-type(3n+1)::before {
    color: green;
}

ul li:nth-of-type(3n+2)::before {
    color: blue;
}

ul li:nth-of-type(3n+3)::before {
    color: orange;
}

There is no need to delete the standard bullets and use a before pseudo element now.

The CSS marker pseudo element does it for you.

li::marker {
  color: var(--col);
}
li:nth-child(3n) {
  --col: red;
}
li:nth-child(3n+1) {
  --col: green;
}
li:nth-child(3n+2) {
  --col: blue;
}
<ul>
  <li>one</li>
  <li>two</li>
  <li>three</li>
</ul>

Related