ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
## :first-child 伪元素 ### 定义和用法 :first-child选择器匹配第一个子元素。 :first-child是一个伪类,它适用于任何元素,它是另一个元素的第一个子元素。 使用:first-child伪类,一个元素只有当它是另一个元素的第一个子元素时才匹配。例如,p:first-child将选择作为某个其他元素的第一个子元素的任何p元素。如果要选择段落的第一个子元素,我们可以使用p>\*:first-child。 **例子:** ~~~ body *:first-child {font-weight: bold;} p:first-child {font-size: 125%;} ~~~ ## 实例--匹配属于父元素中第一个子元素的每个元素 ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>W3Cschool教程(w3cschool.cn)</title> <style> p:first-child { background-color:yellow; } </style> </head> <body> <p>This paragraph is the first child of its parent (body).</p> <h1>Welcome to My Homepage</h1> <p>This paragraph is not the first child of its parent.</p> <div> <p>This paragraph is the first child of its parent (div).</p> <p>This paragraph is not the first child of its parent.</p> </div> <p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p> </body> </html> ``` ## 实例2--元素是其父级的第一个子元素,每个元素的 元素的样式: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>W3Cschool教程(w3cschool.cn)</title> <style> p:first-child i { background:yellow; } </style> </head> <body> <p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p> <p>I am a <i>strong</i> man. I am a <i>strong</i> man.</p> <p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p> </body> </html> ``` ## 实例3--列表中的第一个 元素选择的样式: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>W3Cschool教程(w3cschool.cn)</title> <style> li:first-child { background:yellow; } </style> </head> <body> <ul> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <ol> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ol> <p><b>注意:</b> :first-child作用于IE8以及更早版本的浏览器, DOCTYPE必须已经声明</p> </body> </html> ``` ## 实例4--每一个元素的第一个子元素选择的样式:: ``` <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>W3Cschool教程(w3cschool.cn)</title> <style> ul>:first-child { background:yellow; } </style> </head> <body> <ul> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <ul> <li>Coffee</li> <li>Tea</li> <li>Coca Cola</li> </ul> <p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p> </body> </html> ```