Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

html - CSS Nested lists items and alternate background

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...