使用CSS根据兄弟元素的个数来调整样式

稀土永磁
使⽤CSS 根据兄弟元素的个数来调整样式
在某些场景下,我们需要根据兄弟元素的总数来为它们设置样式。最常见的场景就是,当⼀个列表不断延长时,通过隐藏控件或压缩控件等⽅式来节省屏幕空间,以此提升⽤户体验。为保证⼀屏内容能展⽰更多的内容,需要将多余的列表项隐藏。
⼆级导航菜单:当菜单项为 1 项时,宽度为 100%;当菜单项为 2 项时,每项宽度为 50%;当菜单项为 3 项时,每项宽度为 33.33333333%;当菜单项为 4 项及以上时,宽度不定,根据内容宽度调整,超出屏幕后滑动菜单查看隐藏的菜单。
不过,对 CSS 选择符来说,基于兄弟元素的总数来匹配元素并不简单。
⼀、设想⼀个列表,假设仅当列表项的总数⼤于 3 时就隐藏项⽬数 4 及之后的项。我们可以⽤ l i:nth-of-type(4)来选中列表的第四个列表项,再使⽤ ~
选择符选择后续的兄弟元素。
⾸页的产品中⼼仅展⽰四项,想要查看更多就需要点击“更多产品+”跳转到产品页,假如循环出的列表总数超过 4 项就隐藏
⼆、设想⼀个⼆级菜单,当列表项总数⼩于 5 时,菜单的宽度按照屏幕的宽度⽐例平均分配,当列表项⼤于等于 5
时,按照⾃⾝内容宽度⾃适应。
企业年度检验办法
li {      &:nth-of-type(4) ~ li {        display: none ;      }    }
硅谷杂志
以第⼀个只有两项的列表为例,我们需要选择每⼀项,并且把其宽度设置为50%。要怎么选择两项中的每⼀项呢,似乎没有办法只能使⽤脚本来判断。不过 li:only-of-type 表⽰⽗元素只有⼀个同⼀类型的⼦元素,它等同于 li:first-of-type:last-of-type 的集合,既是第⼀项⼜是最后⼀项,那我们就选中了只有⼀个项⽬时的这⼀项。⽤同样的思路,li:first-of-type:nth-last-of-type(2) 集合,表⽰既是第⼀项⼜是倒数第⼆项,那我们就选中了有两个项⽬时的第⼀项了,那么 li:first-of-type:nth-last-of-type(2) , li:first-of-type:nth-last-of-type(2)  ~ li 就选中了有两个项⽬时的每⼀项:如果⼀个列表有 3 项,把其宽度设置为 33.33333333%。
可以使⽤ SCSS 预编译器来处理
扩展
上⾯调⽤中我们的⽬的是选择有 1 - 4 项的列表。如果能够调⽤⼀次就省⼼了。
需求:
当项⽬列表为 1 - 4 项时,将字体加粗
母液受启发 first-of-type:nth-last-of-type(n + 5) 限定了最⼩项⽬数为 5,那可不可以限定最⼤项⽬数呢,n 为负数可以实现限定最⼤数,但是 n 不可能为负数,不过可以给 n 取反。
first-of-type:nth-last-of-type(n + 5):nth-last-of-type(-n + 10) 集合中,当 n 取 0  时,-n + 10 最⼤,为 10,这时它表⽰范围为 5 - 10 的项⽬个数。
因此我们实现需求:
itgli {  &:first-of-type:nth-last-of-type(2),    &:first-of-type:nth-last-of-type(2) ~ li {    width: 50%;        }  }
li {  &:first-of-type:nth-last-of-type(3),    &:first-of-type:nth-last-of-type(3) ~ li {    width: calc(100% / 3);        }  }
@mixin n-items($n) {  &:first-of-type:nth-last-of-type(#{$n }),  &:first-of-type:nth-last-of-type(#{$n }) ~ &{    width : calc(100% / #{$n });  }}
伊犁师范学院学报
.sub-nav-item {  @include n-items(1);  @include n-items(2);  @include n-items(3);  @include n-items(4);  &:first-of-type:nth-last-of-type(n + 5),  &:first-of-type:nth-last-of-type(n + 5) ~ & {    padding-right: .15rem ;    padding-left : .15rem ;  }}
.sub-nav-item {  &:first-of-type:nth-last-of-type(n + 1):nth-last-of-type(-n + 4),  &:first-of-type:nth-last-of-type(n + 1):nth-last-of-type(-n + 4) ~ .sub-nav-item  {    font-weight: 500;  }}
这时我们实现了根据兄弟元素的个数范围来设置样式
未加粗,此时有 6 项。
加粗,此时有 4 项。
加粗,此时有 3 项。

本文发布于:2024-09-20 15:33:59,感谢您对本站的认可!

本文链接:https://www.17tex.com/xueshu/693645.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:列表   元素   宽度   兄弟
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议