响应式设计之子元素的数目检测

在响应式设计中,通用做法是根据屏幕尺寸,显示不用的样式。如果碰到需求,希望根据子节点的个数,显示不同的样式呢?

<ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
    <li>5</li>
</ul>
js 判断
js 判断,比较简单,使用场景是:可以先用js 判断,然后再根据判断结果渲染

css 判断
还能通过css 来判断?
直接来结果

有2个节点

li:first-child:nth-last-child(2),
li:first-child:nth-last-child(2) ~{
    // 有两个节点的样式
}
原理,第一行,选择的节点是: 第一个,并且是倒数第二个
第二行,选择的节点是: 第一个,并且是倒数第二个的后面的兄弟节点

大于2个节点

li:first-child:nth-last-child(3+n),
li:first-child:nth-last-child(3+n) ~{
    // 大于两个节点的样式
}
原理,同上

scss 封装

抽象成scss 的mixin ,如下:

@mixin child-equal($childTag,$count){
    #{$childTag}:first-child:nth-last-child(#{$count}),
    #{$childTag}:first-child:nth-last-child(#{$count}) ~ #{$childTag}{
        @content;
    }
}
@mixin child-more-than($childTag,$count){
    #{$childTag}:first-child:nth-last-child(n+ #{$count+1}),
    #{$childTag}:nth-last-child(n+ #{$count+1}) ~#{$childTag}{
        @content;
    }
}
使用方法:

当li 个数多余5个时,宽度为15%;

    @include child-more-than(li,5){
        width: 15%;
    }
当然也有缺点,css 选择器,只能修改子节点本身的样式,不能修改父元素的样式。碰到这种情况,还是得靠万能的js。