CSS :first-child 选择器 详解
css3基础 2023-07-22 16:40:052小码哥的IT人生shichen
CSS :first-child 选择器
实例
选择属于其父元素的首个子元素的每个 <p> 元素,并为其设置样式:
p:first-child { background-color:yellow; }
完整实例:
<!DOCTYPE html> <html> <head> <style> p:first-child { background-color:yellow; } </style> </head> <body> <p>这个段落是其父元素(body)的首个子元素。</p> <h1>欢迎访问我的主页</h1> <p>这个段落不是其父元素的首个子元素。</p> <div> <p>这个段落是其父元素(div)的首个子元素。</p> <p>这个段落不是其父元素的首个子元素。</p> </div> <p><b>注释:</b>对于 IE8 及更早版本的浏览器中的 :first-child,必须声明 <!DOCTYPE>。</p> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
浏览器支持
选择器 | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
:first-child | 4.0 | 7.0 | 3.0 | 3.1 | 9.6 |
注释:对于 IE8 及更早版本的浏览器中的 :first-child,必须声明 <!DOCTYPE>。
定义和用法
:first-child 选择器用于选取属于其父元素的首个子元素的指定选择器。
更多实例
例子 1
选择每个 <p> 中的每个 <i> 元素并设置其样式,其中的 <p> 元素是其父元素的第一个子元素:
p:first-child i { background:yellow; }
完整实例:
<!DOCTYPE html> <html> <head> <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>对于 IE8 及更早版本的浏览器中的 :first-child,必须声明 <!DOCTYPE>。</p> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
例子 2
选择列表中的第一个 <li> 元素并设置其样式:
li:first-child { background:yellow; }
完整实例:
<!DOCTYPE html> <html> <head> <style> li:first-child { background:yellow; } </style> </head> <body> <ul> <li>咖啡</li> <li>茶</li> <li>可口可乐</li> </ul> <ol> <li>咖啡</li> <li>茶</li> <li>可口可乐</li> </ol> <p><b>注释:</b>对于 IE8 及更早版本的浏览器中的 :first-child,必须声明 <!DOCTYPE>。</p> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
例子 3
设置每个 <ul> 的首个子元素,并设置其样式:
ul>:first-child { background:yellow; }
完整实例:
<!DOCTYPE html> <html> <head> <style> ul>:first-child { background:yellow; } </style> </head> <body> <ul> <li>咖啡</li> <li>茶</li> <li>可口可乐</li> </ul> <ol> <li>咖啡</li> <li>茶</li> <li>可口可乐</li> </ol> <p><b>注释:</b>对于 IE8 及更早版本的浏览器中的 :first-child,必须声明 <!DOCTYPE>。</p> </body> </html>
可以使用本站在线JavaScript测试工具测试上述代码运行效果:http://www.phpcodeweb.com/runjs.html
相关页面
CSS 教程:CSS 伪类