2017-02-15 88 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>

相關問題