在使用css伪类first-child时,有时候first-child并不生效
比如下面一段简单的代码
<html> <head> <style type="text/css"> p:first-child {color: red; } </style> </head> <body> <h5>标题</h5> <p>段落 1</p> <p>段落 2</p> </body> </html>
这个时候段落 1没有红色属性
:first-child并不生效,这是为什么?
再来看看这段代码:
<html> <head> <style type="text/css"> p:first-child {color: red;} </style> </head> <body> <h5>标题</h5> <div> <p>段落 1</p> <p>段落 2</p> </div> </body> </html>
:first-child有效,段落1为红色字体,
为什么实例1中无效,在实例2中就有效果呢?
这是因为:first-child只作用于某标签内的第一个子标签:
:first-child选择的是某个标签内的第一个元素
:first-child只有当元素是其父元素的第一个子元素时才能匹配,即该元素前面没有兄弟标签。
<style type="text/css"> td:first-child {color:red} p:first-child {color: red} span:first-child {color:red} </style> <table border="1" cellpadding="6"> <tr> <td>row 1 coll 1</td> <td>row 1 coll 2</td> </tr> <tr> <td>row 2 coll 1</td> <td>row 2 coll 2</td> </tr> </table> <p>我是正常色,因为我前面有兄弟标签</p> <div> <p>我是红色,因为我前面没有兄弟标签</p> <div> <span>我是红色,我是div标签内的第一个span</span> <span>我是正常色,因为我是第二个span</span> </div> <p> <span>我是红色,我是p标签内的第一个span</span> <span>我是正常色,因为我是第二个span</span> </p> </div>