伪类
状态伪类
- :link 应用于未被访问过的链接;
- :hover 应用于鼠标悬停到的元素;
- :active 应用于被激活的元素;
- :visited 应用于被访问过的链接
上述这4个的书写顺序:love hate(记忆方便)
结构伪类(css3新增选择器)
- :first-child 匹配父元素中第一个子元素
- :last-child 匹配父元素中最后一个子元素
- :only-child 匹配父元素中仅有一个子元素的p元素
- :nth-child(n) :匹配属于其父元素的第 N 个子元素,不论元素的类型
- :nth-of-type(n) : 匹配属于父元素的第 N 个特定类型的子元素
<style>
/* 匹配父元素中第一个子元素*/
p:first-child {
background-color: yellow;
}
/* 匹配父元素中最后一个子元素*/
p:last-child {
background: pink;
}
/* 匹配父元素中仅有一个子元素的p元素 */
p:only-child {
background: red;
}
</style>
<body>
<p>This paragraph is the first child of its parent (body).</p>
<div>
<p>This paragraph is the only child of its parent(div).</p>
</div>
<p> paragraph </p>
<div>
<p>This paragraph is the first child of its parent (div).</p>
<p>This paragraph is the last child of its parent(div).</p>
</div>
<p><b>注意:</b> Internet Explorer 8以及更早版本的浏览器不支持 :only-child选择器.</p>
<p><b>注意:</b> :first-child作用于 IE8以及更早版本的浏览器, DOCTYPE必须已经声明.</p>
</body>
:nth-child(n)与:nth-of-type(n)
<ul>
<p>段落1</p>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
要选择ul中的第1个li元素的写法:
li:nth-child(2)或者li:nth-of-type(1)
二者的区别就是:
li:nth-child(n) 先考虑是父元素的第n个子元素的li
li:nth-of-type(n) 就是父元素的第n个li
伪元素
::before和::after
主要用来给元素的前面或后面插入内容,常用”content”配合使用
总结:
伪类:通常用作CSS选择器去设置更多的样式之类;
伪元素:创建一个有内容的虚拟容器;