css3 巧用結構性偽類別選取器

來源:互聯網
上載者:User

標籤:

最近在國外的一個網站上看到的一個關於結構性偽類別選取器的用法,覺得十分實用,就自己嘗試了一下,並把它給記錄下來:

這是最基本的樣式:

 1 <style type="text/css"> 2     li{ 3         list-style-type: none; 4         float: left; 5         width: 60px; 6         height: 60px; 7         background-color: #979698; 8         margin-left: 10px; 9         text-align: center;10         line-height: 60px;11         border-radius: 50%;13     }14 </style>

body內的內容:

 1 <body> 2  <ul> 3      <li>第01個</li> 4      <li>第02個</li> 5      <li>第03個</li> 6      <li>第04個</li> 7      <li>第05個</li> 8      <li>第06個</li> 9      <li>第07個</li>10      <li>第08個</li>11      <li>第09個</li>12      <li>第10個</li>13      <li>第11個</li>14  </ul>15 </body>

首先是最基本的結構性偽類別選取器的用法:

1     li:nth-child(8){2         background-color: #298EB2;4     }

結果展示為:

 

利用:nth-child(n+6) 相當於:nth-child(6)及以上的li標籤元素:

1     li:nth-child(n+6){2         background-color: #298EB2;4     }

結果展示為:

 

同理利用:nth-child(-n+6) 相當於:nth-child(6)及以下的li標籤元素:

1     li:nth-child(-n+6){2         background-color: #298EB2;4     }

結果展示為:

 根據以上原理我們可以來一些進階的:

比如可以利用 nth-child(n+4):nth-child(-n+8) 達到擷取:nth-child(4)及以上和:nth-child(8)及以下的li標籤元素:

1     li:nth-child(n+4):nth-child(-n+8){2         background-color: #298EB2;3     }

結果展示為:

 

還可以利用 :nth-child(n+2):nth-child(odd):nth-child(-n+8) 擷取:nth-child(n+2)到:nth-child(-n+8)之間的單數li標籤元素:

1     li:nth-child(n+2):nth-child(odd):nth-child(-n+8){2         background-color: #298EB2;3     }

結果展示為:

最後我們還可以利用:nth-child(3n+1)擷取數目為1、4、7、10中的偶數li標籤元素:

1     li:nth-child(3n+1):nth-child(even){2         background-color: #298EB2;3     }

結果展示為:

 

css3 巧用結構性偽類別選取器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.