I always look for ways to enhance my projects’ user experience (UX). One effective technique I’ve discovered is using color to improve visual hierarchy, particularly in lists. In this post, I want to share my experience with implementing alternating colors for list items using CSS, which made my web applications more aesthetically pleasing and easier to navigate.
The Original CSS Code
Initially, I had a simple CSS rule that styled my list items (<li>
) with a uniform yellow background color. Here’s the original code I started with:
ul li {
cursor: pointer;
margin: 5px 0;
padding: 10px;
background-color: #eeff00; /* Yellow color */
transition: background-color 0.3s;
border-radius: 5px;
width: 80%; /* Consistent width */
margin-left: auto; /* Centers the list items */
margin-right: auto; /* Centers the list items */
}
In this code, I set each list item to have a yellow background (#eeff00
). The cursor: pointer;
property indicated that the items were interactive, which enhanced usability. Additionally, I used margins and paddings to ensure consistent spacing and a pleasant layout.
While this style worked well, I realized that it lacked visual variety. Without differentiation, it became harder for users to distinguish between items quickly.
Enhancing with Alternating Colors
To improve this, I decided to use the nth-child
pseudo-class in CSS. This feature allowed me to style specific items based on their position in the list. Here’s the updated CSS that I implemented:
ul li {
cursor: pointer;
margin: 5px 0;
padding: 10px;
transition: background-color 0.3s;
border-radius: 5px;
width: 80%; /* Consistent width */
margin-left: auto; /* Centers the list items */
margin-right: auto; /* Centers the list items */
}
ul li:nth-child(odd) {
background-color: #eeff00; /* Yellow for odd items */
}
ul li:nth-child(even) {
background-color: #4CAF50; /* Green for even items */
}
How It Works
- Base Styles: I kept the base styles for the list items unchanged, ensuring a consistent layout and interaction feedback with the cursor style.
- Alternating Colors:
- The
ul li:nth-child(odd)
rule applies to all odd-numbered list items (1st, 3rd, 5th, etc.), setting their background color to yellow. - The
ul li:nth-child(even)
rule applies to even-numbered list items (2nd, 4th, 6th, etc.), setting their background color to green.
- The
This approach enhanced the list’s visual appeal and usability. Users could easily scan through the items without confusion, as the alternating colors clearly distinguished each entry.
You may check out the code source for the app I’ve used this technique for here: https://github.com/NoToolsNoCraft/Simple-API-Testing-Simulator