首页 > 技术文章 > 伪类选择器 :nth-child(even) :nth-child(odd) :nth-of-type

mkl7 2019-05-22 19:06 原文

属性描述CSS
:active 向被激活的元素添加样式。 1
:focus 向拥有键盘输入焦点的元素添加样式。 2
:hover 当鼠标悬浮在元素上方时,向元素添加样式。 1
:link 向未被访问的链接添加样式。 1
:visited 向已被访问的链接添加样式。 1
:first-child 向元素的第一个子元素添加样式。 2
:lang 向带有指定 lang 属性的元素添加样式。 2

 

 

伪类专门用来表示元素的一种的特殊状态

当我们需要为处在这些特殊状态的元素设置样式时, 就可以使用伪类

a:link {color: #FF0000}		/* 未访问的链接 */
a:visited {color: #00FF00}	/* 已访问的链接 */
a:hover {color: #FF00FF}	/* 鼠标移动到链接上 */
a:active {color: #0000FF}	/* 选定的链接 */

 

:first-child 伪类

 :first-child 伪类来选择元素的第一个子元素

例子 1 - 匹配第一个 <p> 元素

在下面的例子中,选择器匹配作为任何元素的第一个子元素的 p 元素:

<html>
<head>
<style type="text/css">
p:first-child {
  color: red;
  } 
</style>
</head>

<body>
<p>some text</p>
<p>some text</p>
</body>
</html>

 

例子 2 - 匹配所有 <p> 元素中的第一个 <i> 元素

在下面的例子中,选择器匹配所有 <p> 元素中的第一个 <i> 元素:

<html>
<head>
<style type="text/css">
p > i:first-child {
  font-weight:bold;
  } 
</style>
</head>

<body>
<p>some <i>text</i>. some <i>text</i>.</p>
<p>some <i>text</i>. some <i>text</i>.</p>
</body>
</html>

例子 3 - 匹配所有作为第一个子元素的 <p> 元素中的所有 <i> 元素

在下面的例子中,选择器匹配所有作为元素的第一个子元素的 <p> 元素中的所有 <i> 元素:

<html>
<head>
<style type="text/css">
p:first-child i {
  color:blue;
  } 
</style>
</head>

<body>
<p>some <i>text</i>. some <i>text</i>.</p>
<p>some <i>text</i>. some <i>text</i>.</p>
</body>
</html>

 

 

为p标签中选中的内容使用样式

可以使用::selection伪类

(具有浏览器兼容性问题)

 

-------------------------------------------------------

:first-child   可以选中第一个子元素

:last-child   可以最后一个子元素

:nth-child() 可以选中任意位置的子元素 , 该选择器后面可以指定一个参数, 指定选定第几个子元素

 

:nth-child(even)  选中偶数位置的子元素

:nth-child(odd)  选中奇数位置的子元素

可用于表格隔行变色

 
 
 

:first-of-type

:last-of-type

:nth-of-type

在当前类型的子元素中排列

 

推荐阅读