CSS学习:伪类、伪元素

伪类

它的作用就像 类,但并没有出现在所标记的标签上

表示元素状态的伪类

1
2
/* Mouse 放在 a 标签上方时 text-decoration 为 none */
a:hover {text-decoration: none;}

类似的伪类还有

1
2
3
a:link {color: black;}
a:visited {color: gray;}
a:active {color: red;}

还有一种伪类 和结构相关

1
2
/* 同胞元素中第一个 li 元素 的 color 设置为 blue */
li:first-child {color: blue;}

类似的还有

1
2
:last-child
:nth-child

nth-child 可以参考 CSS 选择器 :nth-child 用法


伪元素

1
2
/* p 里的第一个 letter 的字体大小为 300% */
p::first-letter {font-size: 300%;}

如果不用伪元素创建这个首字符放大效果,必须手工给该字母加上标签, 然后再为该标签应用样式。而伪元素实际上是替我们添加了无形的标签

更为常见的伪元素是

1
2
::before 
::after

可用于在特定元素前面或后面添加特殊内容。

如:

1
2
3
<p class="age">25</p>

p.age::after {content:" years.";}

可以得到 25 years.


注意

first-childfirst-letter 这种类型的,直观的看并不好区分它是伪类还是伪元素

所以必须清楚伪类和伪元素代表的是什么

  • first-child 描述的是某种元素,是在元素之外,作用就像「类」

  • first-letter first-line 描述的是元素里的某种内容,是在元素之内,作用就像是一种「元素」

原文作者: dgb8901,yinxing

原文链接: https://www.itwork.club/2018/10/30/css-class/

版权声明: 转载请注明出处

为您推荐

体验小程序「简易记账」

关注公众号「特想学英语」

微信网页分享朋友圈