2017-02-15 89 views
0

对于CSS3,我想抓住第一个和第四个兄弟元素 - 只有这两个。找不到工作:nth-of-type(an+b)选择器,因为我不是第一个元素,但我只是在寻找这两个元素。第n和第m兄弟元素的选择器?

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

将不起作用,因为后者的选择器类型会覆盖第一个选择器。似乎有最后一个类型的选择器赢得方法的效果。

我该如何选择CSS3的第一个和第四个兄弟元素?

+0

这似乎做工精细,给出一个实际的元素。 https://jsfiddle.net/j08691/ou5won6k/ – j08691

回答

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>

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>

如果你想获得它只是一个选择完成,这将是它

的第一个元素进行选择(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>

相关问题