如何组合使用CSS first-of-type与:not(:first-child)选择器设置指定元素样式
实现方案
直接使用层级组合选择器即可精准命中目标元素,具体写法如下:
核心选择器逻辑
命中第一个StyledRow容器下的第二个Row子元素,选择器为:.StyledRow:first-of-type > .Row:nth-child(2)
styled-components 集成写法
直接把规则写入StyledRow的样式定义即可:
const StyledRow = styled.div` display: flex; align-items: center; // 原有规则建议优化缩小匹配范围,避免污染其他元素 & > .Row:not(:first-child) { margin-left: 0.2rem; } // 新增自定义样式规则 &:first-of-type > .Row:nth-child(2) { // 此处填写你需要覆盖的自定义样式,示例如下 margin-left: 0.5rem; font-weight: bold; } `;
注意事项
- 如果
StyledRow的同级父容器内还有其他div标签和StyledRow混排,first-of-type会匹配到父容器下第一个div而非第一个StyledRow,此时可以改为使用&:nth-of-type(对应序号),比如第一个StyledRow是父容器下第3个div,就写&:nth-of-type(3)。 - 若每组
StyledRow内固定只有2个Row元素,也可以把.Row:nth-child(2)替换为.Row:last-child,效果一致。
内容的提问来源于stack exchange,提问作者cts
相关产品推荐
相关产品推荐

