CSS :nth-​​child()选择器用法详细示例

2021年3月15日09:34:00 发表评论 846 次浏览

:nth-​​child()CSS中的选择器用于根据元素在一组同级中的位置来匹配元素。它匹配作为第n个子元素的每个元素。

语法如下:

:nth-child(number) {
    //CSS Property
}

其中Number是表示匹配元素的模式的参数。它可以是奇数, 偶数或以功能符号表示。

  • 奇:它代表位置在一系列中为奇数的元素:1、3、5等。
  • 甚至:它表示位置甚至在一系列中的元素:2、4、6等。
  • 功能符号(<An + B>):对于n的每个正整数或零值, 它表示元素的兄弟姐妹位置与模式An + B匹配。

示例1:在此示例中, 选择了每个奇数段。使用的公式为2n + 1, 即选择了1、3、5等段落。

<!DOCTYPE html>
< html >
     < head >
         < title >CSS :nth-child Selector</ title >
         < style > 
             p:nth-child(2n+1) {
               background: green;
               color: white;
             }
         </ style >
     </ head >
     < body style = "text-align:center" >
         < h1 style = "color:green;" >
             lsbin
         </ h1 >
         < h2 >
             CSS :nth-child Selector
         </ h2 >
      
         < p >A computer science portal for geeks.</ p >
         < p >Geeks classes an extensive classroom programme.</ p >
          
     </ body >
</ html >

输出如下:

nthchild

示例2:

在此示例中, 选择了每个偶数<li>, 即2、4、6等。

<!DOCTYPE html>
< html >
     < head >
         < title >CSS :nth-child Selector</ title >
         < style > 
         li {
             width: 30%;
         }
             li:nth-child(even) {
               background: green;
               color: white;
             }
         </ style >
     </ head >
     < body style = "text-align:center" >
         < h2 >
             CSS :nth-child Selector
         </ h2 >
         < p >Sorting Algorithms</ p >
         < ul >
         < li >Quick sort.</ li >
         < li >Merge sort.</ li >
         < li >Insertion sort.</ li >
         < li >Selection sort.</ li >
          
         </ ul >
          
     </ body >
</ html >

输出如下:

nthchild

支持的浏览器:下面列出了:nth-​​child()选择器支持的浏览器:

  • 苹果Safari 3.2
  • 谷歌浏览器4.0
  • Firefox 3.5
  • 歌剧9.6
  • Internet Explorer 9.0

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: