Defining an Array of Colors Using CSS

Join Temani Afif as he explores the use of modern CSS features to create an array of colors. The goal is to define a comma-separated list of colors and iterate through them using an index. While CSS is traditionally known for its property-value pairs, recent advancements in CSS have introduced more robust features such as variables, math formulas, conditional logic, and new pseudo selectors. By combining these features, we can create an array of colors.

To begin, let’s consider a basic use case with two colors defined in a variable: black and white. Instead of using the color-mix() function for its intended purpose of mixing colors, we can use it to return one of the two colors in its argument list. By assigning the array of colors to a variable and updating the index variable, we can select the desired color. This technique can be useful for implementing a dark mode on a website.Moving on to a more exciting example, we can create a multi-value array of colors and variables for it. By defining the number of colors in the array and allowing the index to take any value, we can manipulate a linear gradient background to extract the colors based on the index. The gradient transitions between colors, but by increasing its size, we can zoom in on a specific color. By adjusting the position of the gradient using the index variable, we can select any color from the array.To improve our work, we can remove the restriction on the index and allow it to take any value. By performing a modulo operation using a conical gradient, we can convert the index value into the range [0 N-1]. This allows us to use any integer value for the index, even negative values. We can rotate the gradient to select the desired color, simulating a color wheel.It’s important to note that this approach is more of a hack than a CSS feature, so caution should be exercised when using it. Multiplying things by infinity may have performance and accessibility implications. Additionally, this technique can only be used with the background property, limiting its usage.In conclusion, this CSS experimentation allows us to create an array of colors without adding much code. It showcases the versatility of CSS and its ability to handle arrays. Feel free to explore and share your own creations using this technique.