兄贵选择器

202 阅读1分钟

相邻兄弟选择器 .a + .b 只能选择弟弟 .b 而不能选择 .a,在 Safari 和 Chrome 陆续支持 :has() 选择器后,现在终于有办法选择相邻兄弟中的大哥了,也就是 .a:has(+ .b)

IMG_0310.PNG

考虑以上界面,将连续选中的项目为整体设置圆角,拆分成各项目,也就是如下规则:

  • 连续选中的第一个项目有左上、右上方的圆角。
  • 连续选中的中间项目没有圆角。
  • 连续选中的最后一个项目有左下、右下方有圆角。

写成 CSS 也就是:

@supports selector(:has(+ div)) {
    .item.selected {
        border-top-left-radius: 10px;
        border-top-right-radius: 10px;
    }
    .item.selected + .item.selected {
        border-top-left-radius: 0;
        border-top-right-radius: 0;
    }
    .item.selected:last-child {
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
    }
    .item.selected:has(+ .item:not(.selected)) {
        border-bottom-left-radius: 10px;
        border-bottom-right-radius: 10px;
    }
}