简体   繁体   中英

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.嵌套列表示例

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>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM