第n和第m个兄弟元素的选择器?

时间:2017-02-15 16:54:25

标签: css3 css-selectors

使用CSS3,我想要准确地抓住第一个和第四个兄弟元素 - 而且只有这两个。无法找到有效的:nth-of-type(an+b)选择器,因为我不是在每个第a个元素之后,而是只查找这两个元素。

:nth-of-type(1), // :first-of-type wouldn't work either,
:nth-of-type(4){
  ...
}

不会工作,因为后一种选择器会覆盖第一个选择器。似乎有最后一个类型的选择器胜利方法生效。

如何用CSS3选择第一个和第四个兄弟元素?

2 个答案:

答案 0 :(得分:2)

使用:nth-of-type时,它需要类型或类,例如div:nth-of-type.block:nth-of-type

div:nth-of-type(1),
div:nth-of-type(4){
  color: lime;
}

.block:nth-of-type(1),
.block:nth-of-type(4){
  color: red;
}

/*  for styling purpose  */
div + span { margin-top: 20px; }
.block { display: block; }
<div>Hey there div</div>
<div>Hey there div</div>
<div>Hey there div</div>
<div>Hey there div</div>
<div>Hey there div</div>

<span class="block">Hey there div</span>
<span class="block">Hey there div</span>
<span class="block">Hey there div</span>
<span class="block">Hey there div</span>
<span class="block">Hey there div</span>

答案 1 :(得分:0)

您发布的选择器似乎工作正常

div:nth-of-type(1),
div:nth-of-type(4){
  background-color: red;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>

如果你想在一个选择器中完成它,那就是

第一个元素select(对于n = 0)是第四个,然后是第一个,然后我们去负数

div:nth-of-type(-3n+4){
  background-color: red;
}
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>