Is it possible to achieve N-level zebra striping with CSS3 selectors?

The .less file for .list-striped is set up with a basic zebra striping pattern.

It even works for nested lists by reversing the selectors to avoid duplicate styling of parent and child list items.

However, we are looking to extend this functionality to N-level depths without endlessly nesting styles. Is there a solution using nth-child(even)/nth-child(odd) magic on the nested .list-item?

  • C1
    • C2
      • C1
      • C2
    • C1
      • C2
    • C2
  • C2
  • C1
  • C2

The HTML structure is:

<div class="list-striped">
    <div class="list-item">
        <a class="title">List title</a>

        <!-- Start N-Level Nesting -->
        <div class="list-striped">
            <div class="list-item">
                <a class="title">List title</a>
                <!-- Repeat n-level nesting item here as needed -->
            </div>
        </div>
        <!-- End N-level Nesting -->

    </div>

    <div class="list-item">
        <a class="title">List title</a>

        <!-- Start N-Level Nesting -->
        <div class="list-striped">
            <div class="list-item">
                <a class="title">List title</a>
                <!-- Repeat n-level nesting item here as needed -->
            </div>
        </div>
        <!-- End N-level Nesting -->

    </div>
</div>

And the corresponding CSS:

div {
  .list-striped {

    .list-item:nth-child(odd) {

      a {
        background-color: @tableBackgroundAccent;
      }

      .list-striped {

        .list-item:nth-child(odd) a {
          background-color: @white;
        }

        .list-item:nth-child(even) a {
          background-color: @tableBackgroundAccent;
        }
      }

    }

    .list-item:nth-child(even) {

      a {
        background-color: @white;
      }

      .list-striped {

        .list-item:nth-child(even) a {
          background-color: @white;
        }

        .list-item:nth-child(odd) a {
          background-color: @tableBackgroundAccent;
        }
      }

    }

  }

  &.list-hover {
    .list-item:hover a {
      background-color: @tableBackgroundHover;
    }
  }
}

Answer №1

While this solution is not fully complete in sass, it offers a CSS alternative. Additionally, there is a work-in-progress sass solution provided in the comments below to address your issue.

Check out the code here

Here is the HTML structure:

<ul>
    <li>ho</li>
    <li>ho</li>
    <li>ho
        <ul>
            <li>foo</li>
            <li>foo</li> 
            <li>foo</li>
            <li>foo</li>            
        </ul>
    </li>
    <li>ho
        <ul>
            <li>foo</li>
            <li>foo</li>    
            <li>foo</li>
            <li>foo</li>        
        </ul>
    </li>
    <li>ho</li>
</ul>

And here is the Sass code snippet:

ul {
  > li:nth-child(even) {
    background: red;
    ul li:nth-child(even) {
      background: red;
    }
    ul li:nth-child(odd) {
      background: blue;
    }
  }
  > li:nth-child(odd) {
    background: blue;
    ul li:nth-child(odd) {
      background: red;
    }
    ul li:nth-child(even) {
      background: blue;
    }
  }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get rid of empty spaces in gridstack js

My latest project involves using gridstack js In the image displayed, I have highlighted the excess white space (in blue) that needs to be removed. Take a look at this visual: https://i.sstatic.net/Qgt62.jpg Any suggestions on how to eliminate this ...

Whenever I attempt to execute my .html and .js files, I encounter the error message: "Uncaught SyntaxError: Unexpected token <"

Just starting out in react.js, I decided to include CDN links to compile some basic react.js code into my html. Unfortunately, I encountered this error: "Uncaught SyntaxError: Unexpected token <" I did some research and found a suggestion to add: t ...

What are some ways to enhance mobile browsing with CSS?

I'm facing a challenge with optimizing my webpage for different mobile resolutions in my beginner HTML/CSS course. Whenever I use a website resolution simulator to test, the layout doesn't look right on certain settings. Is there a method to aut ...

When using AngularJS with DateRangePicker, I am encountering an issue where my ng-model does not capture the input text value when I select a date

Trying to establish the selected date range in an ng-model called dateRange in the following HTML. The input text field displays the selected value correctly, but dateRange remains null. What steps can I take to address this issue? <!DOCTYPE html> ...

When the tailwind utilities are implemented, they do not appear on the screen

Recently, I embarked on a project using Tailwindcss/Next.js and encountered an issue when trying to apply a box-like shadow to a button with a new utility in pure CSS. Despite my efforts, the changes don't seem to take effect. Can you spot what I migh ...

Remove a specific div element using the keyword "this" in Javascript

Is there a way to generate a new div by pressing a button, with an option to delete that specific div by clicking on another button within it? I want each new div created by the first button to have its own unique delete button that will only remove its ...

using the image source in the onclick function

I have implemented the following code to convert an image to grayscale using Javascript. <body> <canvas id="myCanvas" width="578" height="400"></canvas> <script> function drawImage(imageObj) { var canvas = document.getElement ...

Toggle Jquery menu with a click of a button

I need help with creating a menu for a forum that opens on click and closes on click. Here is the code I have so far: /*Custom BBPress admin links menu*/ function wpmudev_bbp_admin_links_in_menu($retval, $r, $args) { if ( is_user_logged_in() ) { $me ...

Methods to validate CSS attributes specified within a class using React testing library

I am struggling to validate the CSS properties defined within a class in CSS using the React Testing Library. Unfortunately, I am facing challenges in doing so. Here are the simplified code snippets: import React from "react"; import { render, ...

Is there a minimum height restriction for v-select in Vuetify.js?

Looking at the code snippet provided below, I am facing an issue while trying to decrease the height of a v-select element. It seems like there is a minimum limit set for the height, as reducing it beyond height = 40 doesn't have any effect. Is there ...

Guide to automatically compressing images during the file upload process

Is there a way to automatically compress images larger than 4MB to less than 1MB before uploading them in AngularJS? Any suggestions on how to achieve this? Here is the sample file: JSFIDDLE var myApp = angular.module('myApp', []); myApp.dir ...

Unable to adjust table, row, and cell heights in Outlook template due to HTML/CSS formatting issues

I'm struggling to make the height of the leftmost (commented) nested table adjust automatically based on the content in the right section. It displays correctly in Chrome, but does not stretch in Word/Outlook. Any ideas on how to fix this for Word/Ou ...

How to Send Javascript DOM Value to Inner HTML

I am trying to extract a value from a hidden element ID and set it as the inner HTML for another element ID. Below is my code: <script> function replaceText(){ var x=document.getElementById("mainTitle1").textContent; document.getElementById("mainTi ...

WordPress Migration Causing Issues with Custom Font Display

I recently moved my website from to using the Duplicator plugin, but I'm facing an issue with the custom font 'Kanit' not displaying correctly. I have double-checked on the backend and confirmed that Kanit font is properly set up. Below i ...

TailwindCSS in React.Js does not seem to accept randomly generated color codes

Check out my Messages component below: import randomColor from "random-color"; import React from "react"; import "../Chat.css"; function DisplayMessage({ username, message }) { const changeTextColor = randomColor(0.99, 0.99 ...

What is the reason for the lack of an applied CSS selector?

.colored p{ color: red; } article > .colored{ color:powderblue; } .blue{ color: white; } <!DOCTYPE html> <html lang="ko"> <head> <meta charset="UTF-8> <meta name="viewport" content="width=device-width, initi ...

Converting coordinates to pixel-based fixed positioning in CSS

After creating an animated square pie chart using basic CSS to display it in a grid format, I am now looking to transform the larger squares into a state map grid. Any ideas on how to achieve this? In my JavaScript code snippet below, I believe there is a ...

Tips for setting the color of hyperlinks in a UIWebView

I'm struggling with formatting a short plain text string, which may include a weblink, in a UIWebView. When I use loadHTMLString, the font style and size appear incorrect. After searching extensively, I ended up embedding the text in a makeshift HTML ...

What could be the reason for the discrepancy between my get_token() function and the value obtained from request.META.get("CSRF_COOKIE")?

Can anyone shed light on why I'm facing this particular issue? I am currently exploring the integration of Angular 17 as a Frontend with Django as a Backend. While validating a form, I encountered an issue where the token obtained from Django does no ...

Dynamic backdrop featuring engaging content

I am currently working on a WordPress website that features a dynamic background. While I have successfully implemented movement to the background, the content on the site remains static and unaffected by scrolling. The background does not move alongside t ...