V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Can I use?
http://caniuse.com/
Less
http://lesscss.org
Cool Libraries
Bootstrap from Twitter
Jetstrap
manyfreebug
V2EX  ›  CSS

为什么这段 CSS 的 first-of-type 不起作用?

  •  
  •   manyfreebug · 2022-02-17 17:34:58 +08:00 · 1343 次点击
    这是一个创建于 771 天前的主题,其中的信息可能已经有所发展或是发生改变。

    按照我的理解,这段 CSS 应该作用于.num-wrapper 下的第一个.child 元素(也就是<span class='child'>2</span>),但为什么不起作用?(演示效果: https://jsbin.com/zamumatoce/edit?html,css,output)

    <div class="num-wrapper">
      <span>1</span>
      <span class='child'>2</span>
      <span>3</span>
      <span class='child'>4</span>
    </div>
    
    .child:first-of-type {
      color: blue;
      font-size: 2em;
    }
    
    5 条回复    2022-02-18 09:15:48 +08:00
    gucheen
        1
    gucheen  
       2022-02-17 17:43:06 +08:00   ❤️ 1
    人特性命名都告诉你是 first of **type**,你还在 class 。。。
    noe132
        2
    noe132  
       2022-02-17 17:46:02 +08:00   ❤️ 1
    type 指的是 element type 。
    你的例子里
    :first-of-type 会选择 外层 div ,第 1 个 span
    .child 会选择第 2, 4 个 span
    然后这两个结果取并集,结果就是空集,匹配到了 0 个元素。
    66beta
        3
    66beta  
       2022-02-17 17:48:38 +08:00   ❤️ 2
    不支持类名的方式

    可以这样:
    ```css
    .child {
    color: blue;
    font-size: 2em;
    }
    .child ~ .child {
    color: black;
    font-size: 1em;
    }
    ```
    manyfreebug
        4
    manyfreebug  
    OP
       2022-02-17 21:09:55 +08:00
    @noe132 交集并集的概念你好像弄混了 :( 而且第一次见用集合的概念来解释 first-of-type 之类的
    Felix96
        5
    Felix96  
       2022-02-18 09:15:48 +08:00   ❤️ 1
    一楼原因说的很明确了,
    如果目的只是是单独作用第几个 span 的话,可以这样:

    .num-wrapper>span:nth-of-type(2)
    {
    color: blue;
    font-size: 2em;
    }
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2858 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 14:28 · PVG 22:28 · LAX 07:28 · JFK 10:28
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.