Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am searching for a way to have list items have alternating background colors. When there is a nested list the items keep alternating but the child is indented without having the background color of the parent flow down to its nested children. nested list example

It is not possible to apply classes. Also the amount of items is variable. Preferably it should work for an infinite amount of nested lists. But if that is not possible a cap on 3 depths (as in picture) should be enough. If it is easier to do by using divs instead of li and ul, that is also possible for me. I prefer pure HTML/CSS.

Because all my experiments did no good I can only supply a JSFiddle with the nested lists.

https://jsfiddle.net/qmdwpzt8/1/

<ul>
<li>Item 1
    <ul>
        <li>Item 1-1</li>
        <li>Item 1-2
            <ul>
                <li>Item 1-2-1</li>
                <li>Item 1-2-2</li>
            </ul>
        </li>
        <li>Item 1-3</li>
    </ul>
</li>
<li>Item 2
    <ul>
        <li>Item 2-1
            <ul>
                <li>Item 2-1-1</li>
            </ul>
        </li>
    </ul>    
</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
717 views
Welcome To Ask or Share your Answers For Others

1 Answer

Here is one potential solution: https://jsfiddle.net/qmdwpzt8/3/

Not sure if all your requirements will be met by it, but I updated your list with div's:

<ul>
    <li><div>Item 1</div>
        <ul>
            <li><div>Item 1-1</div></li>
            <li><div>Item 1-2</div>
                <ul>
                    <li><div>Item 1-2-1</div></li>
                    <li><div>Item 1-2-2</div></li>
                </ul>
            </li>
            <li><div>Item 1-3</div></li>
        </ul>
    </li>
    <li><div>Item 2</div>
        <ul>
            <li><div>Item 2-1</div>
                <ul>
                    <li><div>Item 2-1-1</div></li>
                </ul>
            </li>
        </ul>    
    </li>
    <li><div>Item 3</div></li>
    <li><div>Item 4</div></li>
</ul>

And then add background colors with jQuery:

$( document ).ready(function() {
    var b = true;
    $( "div" ).each(function( index ) {
        b = !b;
        if (b) {
            $(this).css("background-color", "#ff0000");
        } else {
            $(this).css("background-color", "#00ff00");
        }            
    });
});

This does depend on jQuery/Javascript.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...