Home  >  Article  >  Web Front-end  >  css里的伪类和伪元素的区分_html/css_WEB-ITnose

css里的伪类和伪元素的区分_html/css_WEB-ITnose

WBOY
WBOYOriginal
2016-06-21 08:49:401417browse

首先来看为w3c给他们的定义:

    伪类:用于向某些选择器添加特殊的效果;

    伪元素:用于将特殊的效果添加到某些选择器。

    。。。。。等于没说!

为了区分伪类和伪元素:

       伪元素和伪类之所以这么容易混淆,是因为他们的效果类似而且写法相仿,但实际上 css3 为了区分两者,已经明确规定了伪类用一个冒号来表示,而伪元素则用两个冒号来表示。


下面用实例来区别两者的不同(用伪类 :first-child 和伪元素 :first-letter 来进行比较。):

伪类 --eg:

//cssp>i:first-child {color: red}
//html<p><i>first</i><i>second</i></p>

 解释:伪类 :first-child 添加样式到第一个子元素

如果我们不使用伪类,而希望达到上述效果,可以这样做:

//css.first-child {color: red}//html<p><i class=first-child>first</i><i>second</i></p>//即我们给第一个子元素添加一个类,然后定义这个类的样式

 伪元素--eg:

//cssp:first-letter {color: red}//html<p>i am stephen lee.</p>

 //伪元素 :first-letter 添加样式到第一个字母

那么如果我们不使用伪元素,要达到上述效果

//css.first-letter {color: red}html<p><span class='first-letter'>i</span> am stephen lee.</p>

 即我们给第一个字母添加一个 span,然后给 span 增加样式。

综上:两者的区别已经出来了:

   伪类的效果可以通过添加一个实际的类来达到,而伪元素的效果则需要通过添加一个实际的元素才能达到,这也是为什么他们一个称为伪类,一个称为伪元素的原因。


参照:http://www.ynpxrz.com/n856180c2022.aspx

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn