blog icon indicating copy to clipboard operation
blog copied to clipboard

CSS篇—— 根据包含的子元素个数,实现不同的样式

Open yangchch6 opened this issue 5 years ago • 0 comments

问题

  • 用CSS选择器实现:根据某元素所包含的子元素个数,分别设置不同的样式。

image

CSS 解决方案

// ul 只有 1 个子元素的样式
li:nth-last-child(1):last-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(1) {
    width:calc(100% / 6);
    color:yellow;
}

效果图如下

image

yangchch6 avatar Dec 27 '19 05:12 yangchch6