css判斷子項目個數

來源:互聯網
上載者:User
這次給大家帶來css判斷子項目個數,css判斷子項目個數的注意事項有哪些,下面就是實戰案例,一起來看一下。

工作時遇到這樣一個問題:根據某元素所包含的子項目個數,分別設定不同的樣式,這個用js可以解決,不過個人認為用css解決可能更簡單一點。這也正好加深了我對css選取器的理解和運用。
demo如下:

如下

完整代碼如下:

<!DOCTYPE html><html><head>    <title>css3</title>    <style type="text/css">        *{            box-sizing:border-box;        }        ul{            width:100%;            margin:0;            padding:0;            font-size: 0;        }        li{            margin:0;            padding:0;            display:inline-block;            vertical-align: top;            font-size: 13px;            border:1px solid red;            height:30px;        }        /*ul只有一個子項目的樣式*/        li:nth-last-child(1):first-child{            width:100%;        }        /*ul有2個子項目的樣式*/        /*li:nth-last-child(2):first-child,  是倒數第二個元素,又是第一個元素,說明li的父元素ul有2個子項目(起到了 判斷某父元素下有幾個子項目 的作用)*/        li:nth-last-child(2):first-child,        /* ~ 選擇位於li:nth-last-child(2):first-child 即 第一個子項目之後的元素*/        li:nth-last-child(2):first-child ~ li{            width:calc(100% / 2);        }        /*ul有3個子項目的樣式*/        /*第一個元素寬度為1/3,字型顏色為藍色*/        li:nth-last-child(3):first-child{            width:calc(100% / 3);            color:blue;        }        /*第一個元素之後的第一個元素(即 有3個子項目的ul 的 第 3 個元素)*/        li:nth-last-child(3):first-child ~ li:nth-last-child(1){            width:calc(100% / 4);            color:red;        }        /*第一個元素之後的第一個元素(即 有3個子項目的ul 的 第 2 個元素)*/        li:nth-last-child(3):first-child ~ li:nth-last-child(2){            width:calc(100% / 6);            color:yellow;        }    </style></head><body>    <ul class="list">        <li>11111</li>    </ul>    <ul class="list">        <li>11111</li>        <li>22222</li>    </ul>    <ul class="list">        <li>11111</li>        <li>22222</li>        <li>33333</li>    </ul></body></html>

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

毛毛蟲爬行動畫怎樣實現

Canvas製作旋轉太極的動畫

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.