HTML Dog
跳至导航

Pseudo Classes

伪类附加到选择器上,以指定选择器的状态或关系。它们的格式为 selector:pseudo_class { property: value; },在选择器和伪类之间用一个冒号分隔。

链接

link 用于针对未访问过的链接visited 用于针对,你猜对了,已访问过的链接,它们是最基本的伪类。

以下代码将根据用户是否曾访问过该页面来为页面上的所有链接应用颜色。


a:link {
    color: blue;
}

a:visited {
    color: purple;
}

动态伪类

动态伪类也常用于链接,可以用来在发生某些事件时应用样式。

当鼠标悬停在盒子上面时更改盒子的样式。

a:active {
    color: red;
}

a:hover {
    text-decoration: none;
    color: blue;
    background-color: yellow;
}

input:focus, textarea:focus {
    background: #eee;
}

第一个子元素

最后(至少在本篇文章中),还有一个 first-child 伪类。只有当某个元素是另一个元素的第一个后代时,它才会生效。因此,在以下 HTML 中…


<body>
    <p>I’m the body’s first paragraph child. I rule. Obey me.</p>
    <p>I resent you.</p>
...

…如果你只想为第一个段落设置样式,可以使用以下 CSS:


p:first-child {
    font-weight: bold;
    font-size: 40px;
}