日期:2014-05-17  浏览次数:20560 次

求解释为什么会这样
下面是dreamweaver的代码
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<style type="text/css">
a:link{font-size:20px;}
a:visited{color:#CCCCCC;}
a:hover{color:#00F;}
a:active{color:#00FF00;}
h1:first-child{color:red; font-size:50px;}

</style>
<body>
<a href="http://www.baidu.com">百度搜索</a>
<h1>www.baidu.com百度搜索</h1>
<h1>百度搜索www.baidu.com</h1>
</body>
</html>
我这样写的时候h1:first-child{color:red; font-size:50px;}不起作用,但是我把<a href="http://www.baidu.com">百度搜索</a>给删除掉的话,h1:first-child{color:red; font-size:50px;}就能起作用,为什么会这样?

------解决方案--------------------
我这边查得的资料是这样的

结构性伪类选择符 E:first-child 版本:CSS2 
语法:
E:first-child{ sRules }
说明:
匹配父元素的第一个子元素E。 
要使该属性生效,E对象必须是某个对象的子元素。 
这里可能存在误解: 
示例代码:

<ul>
<li>列表项一</li>
<li>列表项二</li>
<li>列表项三</li>
<li>列表项四</li>
</ul>在上述代码中,如果我们要设置第一个li的样式,那么代码应该写成li:first-child{sRules},而不是ul:first-child{sRules}。其它相关的伪类都如此。

所以删除a后,h1就是body的第一个子元素了,才符合选择器。
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
<style type="text/css">
a:link{font-size:20px;}
a:visited{color:#CCCCCC;}
a:hover{color:#00F;}
a:active{color:#00FF00;}
h1:first-child{color:red; font-size:50px;}

</style>
<body>
<a href="http://www.baidu.com">百度搜索</a>
<div>
<h1>www.baidu.com百度搜索</h1>
<h1>百度搜索www.baidu.com</h1>
</div>
</body>
</html>