You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何组合使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 00:27:03