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

2022-02-17 17:34:58 +08:00
 manyfreebug

按照我的理解,这段 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;
}
1379 次点击
所在节点    CSS
5 条回复
gucheen
2022-02-17 17:43:06 +08:00
人特性命名都告诉你是 first of **type**,你还在 class 。。。
noe132
2022-02-17 17:46:02 +08:00
type 指的是 element type 。
你的例子里
:first-of-type 会选择 外层 div ,第 1 个 span
.child 会选择第 2, 4 个 span
然后这两个结果取并集,结果就是空集,匹配到了 0 个元素。
66beta
2022-02-17 17:48:38 +08:00
不支持类名的方式

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

.num-wrapper>span:nth-of-type(2)
{
color: blue;
font-size: 2em;
}

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/834580

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX