小伙伴你們是否有碰到以下的情況,排行榜前3名的樣式不一樣,你們是怎麼處理的麼?
本來我也是直接每個文字,單獨定樣式的,感覺這樣好累。趕緊搜搜有啥好方法實現,最開始想到的是ol列表,但是沒辦法控制樣式,遂放棄,繼續深入。著實讓我找到了好方法——CSS計數器
先看個簡單的例子:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
body{counter-reset:num;}
div:after{content: counter(num);counter-increment:num;}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
結果:
1、counter-reset 屬性設置某個選擇器出現次數的計數器的值。默認為 0。利用這個屬性,計數器可以設置或重置為任何值,可以是正值或負值。如果沒有提供 number,則默認為 0。
//定義計數器section,不設置number默認為0 counter-reset:section; //定義計數器section,設置number為1 counter-reset:section 1;
//定義多個計數器,並設置number
counter-reset:section 1 abcnum 3;
2、counter-increment 屬性設置某個選取器每次出現的計數器增量。默認增量是 1。number 可以是正數、零或者負數
//遞增counter+2 counter-increment: counter 2 //遞減counter-2 counter-increment: counter -2 //遞增counter+2,遞減ber-2 counter-increment: counter 2 ber -2
3、counter(name, style),注意跟上面的content不一樣,作用單純的顯示計數。
style:設置遞增遞減顯示的文字,可以是英文字母,或者羅馬文。跟ol列表支持的 list-style-type 值一樣
list-style-type:disc | circle | square | decimal | lower-roman | upper-roman |
lower-alpha | upper-alpha | none | armenian | cjk-ideographic |
georgian | lower-greek | hebrew | hiragana | hiragana-iroha | katakana | katakana-iroha | lower-latin | upper-latin
counter還支持級聯。也就是一個content屬性值可以有多個counter()方法
counters(name, string),string參數為字符串(需要引號包圍的)(必須參數),表示子序號的連接字符串。例如1.1的string就是'.', 1-1就是'-'.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>demo</title>
<style>
.list { padding-left: 20px; counter-reset: tjq; line-height: 1.6; color: #666; }
.h1:before { content: counters(tjq, '-') '. '; counter-increment: tjq; font-family: arial black; }
</style>
</head>
<body>
<div class="list">
<div class="h1">a
<div class="list">
<div class="h1">a-1</div>
<div class="h1">a-2</div>
<div class="h1">a-3</div>
</div>
</div>
<div class="h1">b
<div class="list">
<div class="h1">b-1</div>
<div class="h1">b-2</div>
<div class="h1">b-3</div>
<div class="h1">b-4</div>
</div>
</div>
<div class="h1">c
<div class="list">
<div class="h1">c-1</div>
<div class="h1">c-2</div>
</div>
</div>
</div>
</body>
</html>
效果
具體的小伙伴們可以敲敲代碼試試,自然就懂了其中的邏輯的。說其邏輯還真不知道怎麼說。具體的可以看看何問起網
1、相比傳統的ol,ul列表計數,CSS計數器的優勢就在於靈活與強大,不足就是IE6/IE7不支持。
2、一個元素,如果設置了counter-increment, 但是其display的屬性值是none或者含有hidden屬性(針對支持浏覽器),則此計數值是不會增加的。
css計數器還是有一定的便利的,畢竟現在ie6 7,很多都不去兼容,放可以大膽使用,相對於前面所說的寫死的方法靈活多了。
有時排行榜前幾位會有不同的樣式,大可以用css3(:nth-child) 直接實現
//選取第2個標簽
li:nth-child(2){background:#090}
//選取大於等於4的標簽
li:nth-child(n+4){background:#090}
//選取小於於等於4的標簽
li:nth-child(-n+4){background:#090}
//選取偶數標簽
li:nth-child(2n){background:#090}
//選取奇數標簽
li:nth-child(2n-1){background:#090}
//自定義選取標簽,3n+1表示“隔二取一”
li:nth-child(3n+1){background:#090}
//選取最後一個標簽
li:last-child{background:#090}