一.欢迎来到我的酒馆
讨论css伪类。
二.什么是伪类
伪类(pseudo class)是一种选择器,表示元素的特殊状态。伪类由" : 伪类名"构成。
css语法
selector : pseudo_class {
property : value;
}
例如:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
button:hover{
background-color: pink;
}
</style>
</head>
<body>
<button>这是一个按钮</button>
</body>
</html>
当鼠标悬停在button上面的时候,触发hover伪类,将button的背景颜色设置为pink。
三.常见的伪类
- :first-child伪类。:first-child伪类用于选中元素的第一个子级元素。
div : first-child{
background-color: blue;
}
- :last-child伪类。:last-child伪类用于选中元素的最后一个子级元素。
div : last-child{
background-color: blue;
}
- :nth-child(n)伪类。:nth-child()伪类用于选中元素的第n个子级元素。
/* 选中p标签下的i标签中的第二个i标签 */
p i:nth-child(2){
color: blue;
}
- ::after伪类。::after伪类用于在一个元素之后添加一个content,添加的内容为属性值。
/* 在p元素的结尾添加上一个content,添加的内容为属性值 */
p::after{
content: "added ";
color: green; /*给content添加颜色样式 */
font-weight: bold;
background-color: orange;
}
- ::before伪类。::before伪类用于在一个元素之前添加一个content,添加的内容为属性值。
/* 在button元素的开头添加上一个content,添加的内容为属性值 */
button::before{
content: "before ";
}
四.写在最后
伪类暂时先介绍到这里,如果大家对伪类有疑问或者有什么问题,欢迎大家在博客下方留言。如果有什么错误或者有待提高的地方,欢迎指正。