html - 根据单个容器 SCSS 中 sibling 的数量调整元素大小

标签 html css sass css-selectors

我有这个例子:

<div class="container">
    <div class="item-1"></div>
    <div class="item-2"></div>
    <div class="item-2"></div>
    <div class="item-2"></div>
    <div class="item-3"></div>
    <div class="item-3"></div>
</div>

... item-# 可能高达 48。我想要做的是针对每个独特的 .item-# 并赋予它不同的颜色。

我试着在 SCSS 中玩这个:

@for $i from 1 through 48 {
    .item-#{$i} { 
       &:nth-child(1):nth-last-child(2),
       &:nth-child(2):nth-last-child(1) { 
            color: red; } 
       }
}

...但是没有用。我在这里找到了类似的解决方案:Can CSS detect the number of children an element has? ,但区别在于我需要将所有 .item-# 包装在一个容器中。

我想避免使用 JavaScript。

最佳答案

CSS 不提供根据匹配同一选择器的兄弟元素的数量来匹配元素的能力。见 Can I combine :nth-child() or :nth-of-type() with an arbitrary selector?

目前还没有纯 CSS 解决方法。


Selectors 4 的 :nth-child(An+B of S) 符号将提供这种能力(令人恼火的是,:only-child() 没有等效的功能符号> yet),但你仍然需要提前知道选择器 S。这就是您的 SCSS 将派上用场的地方:

@for $i from 1 through 48 {
    :nth-child(1 of .item-#{$i}):nth-last-child(1 of .item-#{$i}) {
        // Styles
    }
}

令人惊讶的是,虽然 Selectors 4 仍然是一个不稳定的草案,而且除了 Safari 之外还没有人实现了 :nth-child() 的这个扩展,但是它可以在当前版本的 Sass 上正确编译。当然,因为它没有实现,所以它实际上不会起作用。尽管如此,很高兴知道我们将来能够做到这一点(假设 Safari 的实现保持不变并且每个人都效仿)。

关于html - 根据单个容器 SCSS 中 sibling 的数量调整元素大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37220223/

相关文章:

html - 在 Firefox 中存在差距,但在 IE 中没有

css - 如何使用背景:url(data:image/png;base64 with Retina?

ios - 动画延迟在 iOS 上无法正常工作,为什么?

html - 如何将 css 规则分配给具有特定类的第一个元素?

android - Ion 选项卡在桌面和移动设备上呈现不同

html - 内联图像和堆叠

html - 此 css 不适用于 mozilla

javascript - 如何通过右键单击更改行的背景颜色

css - 将噪声图像混合到 CSS 按钮中的目的是什么?

css - 如何有效地使用 bootstrap-sass?