使用CSS选择器来判断列表首行与尾行的方法

时间:2021-11-25
类别:教程 - 网页设计

Html/css 列表项 区分列表首尾

列表项,有时需要判断列表首尾,来筛选设置样式

如上图,三个项有间隔,怎么保证设置了列表项之间的距离后,整体还水平居中显示呢?

.item:not(:first-child) {

  margin-left: 20px;

  1. <!DOCTYPE html> 
  2. <html> 
  3. <head> 
  4. <meta charset="UTF-8"
  5. <title>Document</title> 
  6. <style type="text/css"
  7. .container { 
  8.   width:600px; 
  9.   height:300px; 
  10.   background: rgba(4,0,255,0.50); 
  11. .list-parentOuter { 
  12.   float: left; 
  13.   margin-left: 50%; 
  14. .list-parentInner { 
  15.   position: relative; 
  16.   right: 50%; 
  17.   display: flex; 
  18.   flex-direction: row; 
  19.   justify-items: center; 
  20.   margin-top:50px; 
  21. .item{ 
  22.   height: 120px; 
  23.   width: 120px; 
  24.   border: 1px solid #04D18D; 
  25.   background-color:#04D18D; 
  26.   border-radius: 60px; 
  27.   color:#ffffff; 
  28.   text-align:center; 
  29.   line-height:120px; 
  30.   margin: 0px auto; 
  31. .item:not(:first-child) { 
  32.   margin-left: 20px; 
  33. </style> 
  34.  
  35. </head> 
  36. <body> 
  37. <body> 
  38.   <div class="container"
  39.     <div class="list-parentOuter"
  40.       <div class="list-parentInner"
  41.         <div class="item">AAA</div> 
  42.         <div class="item">BBB</div> 
  43.         <div class="item">CCC</div> 
  44.       </div> 
  45.     </div> 
  46.   </div> 
  47. </body> 
  48. </body> 
  49. </html> 

 以上是CSS :first-child 选择器的用法

:first-child 选择器用于选取属于其父元素的首个子元素的指定选择器。

更多的,还有其它的指定元素选择器:

:last-child  选择属于其父元素最后一个子元素。

:nth-child(2) 选择第二个元素

:nth-last-child(2) 选择倒数第二个元素

还有first-of-type、last-of-type、nth-of-type(2)、nth-last-of-type(2),以类型筛选第一个元素。

更多元素选择器,访问 w3school

    收藏