css中伪类和伪元素的区别

用处

普通基于元素或基于类的样式定义像这样

p {
color: red;
text-align: center;
}
这样

para1 {

text-align: center;
color: red;

}
或这样

.center {
text-align: center;
color: red;
}
可以看到他们都基于html dom树中具体的类,或者元素进行样式定义 ,但如果想对诸如元素状态变化或位置进行样式定义则需要用到伪类(Pseudo Classes)和伪元素(Pseudo Elements)。比如对一个连接访问后其字体显示方式,一个段落第一句话的颜色字体显示方式等时候我们就需要用到伪类和伪元素了。

定义

顾名思义,伪类和伪元素不是真正意义上的html存在的类和元素,他们的存在是为了方便对状态和位置进行样式定义。

伪元素
对html中真实元素不同位置的指代。一般以两个冒号作为开始,具体语法为:

selector::pseudo-element {
property:value;
}

selector.class::pseudo-element {
property:value;
}
示例:定义p元素中内容的第一行为红色小字

p::first-line {
color: #ff0000;
font-variant: small-caps;
}
伪类
对html中物理存在的元素进行动作操作后的状态指代(比如点击后,鼠标移动上面后等),一般以一个冒号做为开始。具体语法如下:

selector:pseudo-class {
property:value;
}

selector.class:pseudo-class {
property:value;
}
示例:定义一个链接访问过后的颜色

a:visited {
color: #00FF00;
}
全家福

css中可以使用的伪类以及伪元素全家福如下:

Selector Example Example description
:link a:link Selects all unvisited links
:visited a:visited Selects all visited links
:active a:active Selects the active link
:hover a:hover Selects links on mouse over
:focus input:focus Selects the input element which has focus
::first-letter p::first-letter Selects the first letter of every <p> element
::first-line p::first-line Selects the first line of every <p> element
:first-child p:first-child Selects every <p> elements that is the first child of its parent
::before p::before Insert content before every <p> element
::after p::after Insert content after every <p> element
:lang(language) p:lang(it) Selects every <p> element with a lang attribute value starting with "it"

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文转载自:众成翻译译者:为之漫笔链接:http://www.zcfy.cc/article/239原文:http...
    极乐君阅读 7,412评论 1 62
  • CSS伪类用于向某些选择器添加特殊的效果。 CSS伪元素用于将特殊的效果添加到某些选择器。 可以明确两点,第一两者...
    曾基锟阅读 1,250评论 0 1
  • 1.CSS 元素选择器 最常见的 CSS 选择器是元素选择器。换句话说,文档的元素就是最基本的选择器。如果设置 H...
    饥人谷_小侯阅读 885评论 0 1
  • 学习CSS的最佳网站没有之一 http://www.w3school.com.cn/tags/index.asp ...
    Amyyy_阅读 1,100评论 0 1
  • absolute position和relative position:https://css-tricks.co...
    前端混合开发阅读 323评论 0 0