伪类是添加到选择器的关键字,指定要选择的元素的特殊状态。
使用伪类,不仅可以根据文档 DOM 树中的内容对元素应用样式,而且还可以根据导航历史这样的外部因素来应用样式(例如:visited
),或者根据内容的状态(表单元素的 :checked
),或者鼠标的位置(例如:hover
让你知道鼠标是否在一个元素上悬浮)来应用样式。
anchor伪类
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>pseudo class</title>
<style>
a:link {color:#000000;} /* 未访问链接*/
a:visited {color:#00FF00;} /* 已访问链接 */
a:hover {color:#FF00FF;} /* 鼠标移动到链接上 */
a:active {color:#0000FF;} /* 鼠标点击时 */
</style>
</head>
<body>
<p><b><a href="/css/" target="_blank">这是一个链接</a></b></p>
<p><b>注意:</b> a:hover 必须在 a:link 和 a:visited 之后,需要严格按顺序才能看到效果。</p>
<p><b>注意:</b> a:active 必须在 a:hover 之后。</p>
</body>
</html>
CSS :first-child 伪类
匹配作为任何元素的第一个子元素的<p>元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>first-child-1</title>
<style>
p:first-child
{
font-weight:bold;
}
</style>
</head>
<body>
<p>This is some text.</p><!--加粗-->
<p>This is some text.</p>
<p><b>注意:</b>对于 :first-child 工作于 IE8 以及更早版本的浏览器, !DOCTYPE 必须已经声明.</p>
</body>
</html>
匹配所有<p> 元素中的第一个 <i> 元素
<head>
<meta charset="utf-8">
<title>first-child-2</title>
<style>
p > i:first-child
{
font-weight:bold;
}
</style>
</head>
<body>
<p>a <i>strong</i> man. a <i>strong</i> man.</p><!--第一个strong斜体加粗,第二个strong只有斜体-->
<p>a <i>smart</i> woman. a <i>smart</i> woman.</p><!--第一个smart斜体加粗,第二个smart只有斜体-->
<p><b>注意:</b> 当 :first-child 作用于 IE8 以及更早版本的浏览器, !DOCTYPE 必须已经定义.</p>
</body>
</html>
匹配所有作为第一个子元素的 <p> 元素中的所有 <i> 元素
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>first-child-3</title>
<style>
p:first-child i
{
font-weight:bold;
}
</style>
</head>
<body>
<p>a <i>strong</i> man. a <i>strong</i> man.</p><!--两个strong斜体加粗-->
<p>a <i>smart</i> woman. a <i>smart</i> woman.</p><!--两个smart只有斜体-->
<p><b>注意:</b> 当:first-child 作用于 IE8 及更早版本的浏览器, DOCTYPE 必须已经定义.</p>
</body>
</html>