codecamp

Pseudo-classes and pseudo-elements

伪类

CSS 伪类是一个以冒号( :),它被添加到选择器的末尾,以指定要在所选元素处于特定状态时对其进行样式化。 例如,您可能希望仅在元素被鼠标指针悬停时对其进行样式化,或者在禁用或检查时选中复选框,或者是DOM树中父元素的第一个子元素。

我们现在不会深入到每一个伪类中 - 学习区域的目标不是以详尽的细节来教你一切,而且你肯定会在后面更详细地介绍其中的一些 适当时。

一个伪类的例子

现在,让我们看一个简单的如何使用这些示例。 首先,HTML代码段:

<a href="https://developer.mozilla.org/" target="_blank">Mozilla Developer Network</a>

然后,一些CSS规则:

/* These styles will style our link
   in all states */
a {
  color: blue;
  font-weight: bold;
}

/* We want visited links to be the same color
   as non visited links */
a:visited {
  color: blue;
}

/* We highlight the link when it is
   hovered (mouse), activated
   or focused (keyboard) */
a:hover,
a:active,
a:focus {
  color: darkred;
  text-decoration: none;
}

现在让我们玩我们刚刚造型的链接!

主动学习:斑马条纹信息列表

再次转向 - 在这个主动学习段中,我们希望您向信息链接列表中添加一些斑马条纹,还可以添加相应的伪类,以便在悬停时为链接设置不同的样式。 您只需编辑本练习中的最后三条规则即可。 一些提示:

  1. You have already seen how to write the second pseudo class for the hover styles.
  2. For the zebra striping you'll need to use a pseudo class like :nth-of-type(), giving the two color rules a slightly different version of the pseudo class to style the even and odd numbered list items. See if you can look up how to do this!

如果发生错误,您可以随时使用重置按钮重置。 如果您遇到问题,请按显示解决方案按钮查看一个潜在的答案。

伪元素

伪元素非常类似于伪类,但它们有所不同。 它们是关键字 - 此时前面有两个冒号( :: ),可以添加到选择器的末尾以选择元素的某个部分。

他们都有一些非常具体的行为和有趣的功能,但挖掘它们全部详细是超越范围现在。

伪元素示例

这里我们只显示一个简单的CSS示例,它选择所有绝对链接之后的空间,并在该空间中添加一个箭头:

<ul>
  <li><a href="https://developer.mozilla.org/en-US/docs/Glossary/CSS">CSS</a> defined in the MDN glossary.</li>
  <li><a href="https://developer.mozilla.org/en-US/docs/Glossary/HTML">HTML</a> defined in the MDN glossary.</li>
</ul>

让我们添加这个CSS规则:

/* All elements with an attribute "href", which values
   start with "http", will be added an arrow after its
   content (to indicate it's an external link) */
[href^=http]::after {
  content: '⤴';
}

我们得到这个结果:

主动学习:一个花哨的段落

接下来的积极学习,我们有一个花哨的段落风格! 所有你必须做的是使用 ::第一行 :: first-letter 伪代码将两个规则集应用到段落的第一行和第一个字母 元素。 这应该将段落的第一行以粗体和第一个字母作为一个漂亮的下降帽,给它一个老式的感觉。

如果发生错误,您可以随时使用重置按钮重置。 如果您遇到问题,请按显示解决方案按钮查看一个潜在的答案。

下一步

我们将通过查看组合器和多个选择器来整理CSS选择器的游览。

Attribute selectors
Combinators and multiple selectors
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录
CSS

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }