How To Alternate Colors In Css

Alternating colors in your website design can improve readability and user experience, especially when dealing with tables, lists or long blocks of text. In this blog post, we will show you how to achieve this using CSS.

1. Alternating colors using nth-child selector

The most common method for alternating colors in CSS is using the nth-child selector. This selector allows you to target specific elements based on their position in a group of elements. To alternate the background color of rows in a table, you can use the following CSS code:

    tr:nth-child(even) {
        background-color: #f2f2f2;
    tr:nth-child(odd) {
        background-color: #ffffff;

This code targets every even and odd row in the table and applies a specific background color to them. You can adjust the colors to match your website design.

2. Alternating colors using CSS classes

Another way to alternate colors in CSS is by using classes. This method is more manual but can be useful when you want more control over which elements get specific styles. To do this, you can create two CSS classes with different background colors, like this:

    .even {
        background-color: #f2f2f2;
    .odd {
        background-color: #ffffff;

Then, apply these classes to the appropriate elements in your HTML markup. For example, if you want to alternate the background color of list items, your HTML code should look like this:

        <li class="odd">Item 1</li>
        <li class="even">Item 2</li>
        <li class="odd">Item 3</li>
        <li class="even">Item 4</li>

Remember to manually add the even and odd classes to each element you want to have alternating colors.


Alternating colors in CSS is a simple and effective way to improve the readability and user experience of your website. By using the nth-child selector or applying CSS classes manually, you can create a visually appealing and easy-to-navigate website layout. Experiment with different color combinations to find the perfect look for your site!