您好,欢迎访问一九零五行业门户网

css判断子元素个数

这次给大家带来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>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
毛毛虫爬行动画怎样实现
canvas制作旋转太极的动画
以上就是css判断子元素个数的详细内容。
其它类似信息

推荐信息