/*ul的第一个子元素*/
ul li:first-child{
background: #0f35ad;
}
/*ul的最后一个子元素*/
ul li:last-child{
background: #0f35ad;
}
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>Title</title>
-
- <style>
- /*ul的第一个子元素*/
- ul li:first-child{
- background: #0f35ad;
- }
- /*ul的最后一个子元素*/
- ul li:last-child{
- background: #0f35ad;
- }
- </style>
- </head>
- <body>
- <h1>h1</h1>
- <p>p1</p>
- <p>p2</p>
- <p>p1</p>
- <ul>
- <li>l1</li>
- <li>l2</li>
- <li>l3</li>
- </ul>
- </body>
- </html>
浏览器翻译如下:
/*定位到父元素,选择当前的第一个元素,选择当前p元素的父级元素,选中父元素的第一个,并且是当前元素才有效*/
p:nth-child(1){
background: #0f35ad;
}
注意:如果第一个不是当前元素无效

浏览器翻译如下:


浏览器翻译如下:
