This time I will bring you css to determine the number of sub-elements. What are the precautions for css to determine the number of sub-elements? The following is a practical case, let’s take a look.
I encountered such a problem while working: setting different styles according to the number of sub-elements contained in an element. This can be solved with js, but I personally think it may be easier to solve with css. This also just deepens my understanding and application ofcss selector. Demo is as follows:
##Rendering As follows
The complete code is as follows:
<!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>
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How to realize caterpillar crawling animationCanvas creates rotating Tai Chi animationThe above is the detailed content of css determines the number of child elements. For more information, please follow other related articles on the PHP Chinese website!