我想在無序列表中選擇前兩個列表項。我可以這樣選擇第一項:n-child()還是第一個孩子?如何在一箇中選擇第一個和第二個孩子
ul li:nth-child(1) a {
background: none repeat scroll 0 0 beige;
}
OR
ul li:first-child a {
background: none repeat scroll 0 0 beige;
}
我想選擇這兩個第一和第二行項目 - 我該怎麼做呢?
我想在無序列表中選擇前兩個列表項。我可以這樣選擇第一項:n-child()還是第一個孩子?如何在一箇中選擇第一個和第二個孩子
ul li:nth-child(1) a {
background: none repeat scroll 0 0 beige;
}
OR
ul li:first-child a {
background: none repeat scroll 0 0 beige;
}
我想選擇這兩個第一和第二行項目 - 我該怎麼做呢?
在不使用JS或:nth-child
(我認爲在IE不支持)
ul li:first-child, ul li:first-child + li {
list-style: none;
}
Here的是在IE7
這適用於IE9 +,但它不是最短的。 @ BoltClock的選擇器是IE9 +的最短解決方案。我認爲這個比較容易理解,所以我會把它作爲一個選擇。
ul li:first-child a, ul li:nth-child(2) a
{
background: none repeat scroll 0 0 biege;
}
謝謝。所以我必須用逗號分隔每個選擇器 - 沒有辦法在同一個選擇器中選擇兩個選擇器?我一直在思考一些問題:nth-child(1,2)a - 當然這不起作用,但我認爲可能有類似的東西嗎? – 2012-01-11 14:53:27
@tvanfosson:使用'an + b',你可以簡單地傳遞一個負面的'a',它會只拾取第一個'b'子。看到我的答案。 – BoltClock 2012-01-11 15:00:02
@BoltClock - 我每天都會學到新的東西。 +1給你,但我會把它留在這裏(經過一些考慮),因爲我認爲這很容易理解發生的事情。 – tvanfosson 2012-01-11 15:37:14
對於跨瀏覽器兼容性,最好的選擇是使用jQuery併爲列表項分配一個類。
喜歡的東西...
$(function() {
$('li').each(function() {
if($(this).index() == 1 || $(this).index() == 2) {
$(this).addClass('first_or_second');
}
});
});
瀏覽器沒有JavaScript? – 2012-01-11 14:53:58
選擇第一和第二的孩子,你可以使用一個:nth-child()
僞類,像這樣:
ul li:nth-child(-n+2) a {
background: none repeat scroll 0 0 beige;
}
不錯。我不知道如何使用'a = -1'。 – tvanfosson 2012-01-11 15:03:31
.trJobStatus ul{
width: 500px;
height:500px;
float: left;
}
.trJobStatus ul li{
width: 50px;
height:50px;
border: solid 1px #ddd;
list-style:none;
display: inline-block;
text-align: center;
line-height:50px;
font-size:25px;
}
.trJobStatus ul li:nth-child(1),
.trJobStatus ul li:nth-child(5){
color:red;
}
<div class="trJobStatus">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
.trJobStatus UL測試演示li:nth-child(1), .trJobStatus ul li:nth-child(2){ color:#fff; background-color:#ddd; }
對於':first-child'和鄰接的兄弟選擇器+1,非常適合一直到IE7的兼容性。 – BoltClock 2012-01-11 15:09:51