区分
伪元素在CSS3
之前就已经存在,只是没有伪元素的说法,都是归纳为伪类,所有很多人分不清楚伪类和伪元素。比如常用的:before
和:after
,它们是伪类还是伪元素?其实在CSS3
之前被称为伪类,直到CSS3
才正式区分出来叫伪元素
那如何区分伪元素和伪类,记住两点:
1. 伪类表示被选择元素的某种状态,例如:hover
2. 伪元素表示的是被选择元素的某个部分,这个部分看起来像一个独立的元素,但是是"假元素",只存在于css中,所以叫"伪"的元素,例如:before
和:after
核心区别在于,是否创造了“新的元素”
3、常见的一些应用
1)包括before、after、first-letter、first-line ,分别表示元素内容的前面、元素内容的后面以及第一个文字和第一行文字
<style>
.wrap{
height: 100px;
width: 500px;
border: 1px rgb(5, 248, 114) solid;
padding: 10px;
display: flex;
flex-direction: column;
}
.box1:before{
content: "我是前面的before";
color: rgb(177, 81, 13);
}
.box1:after{
content: "我是后面的after";
color: rgb(243, 29, 72);
}
.box1{
background: rgb(221, 132, 214);
background-clip: content-box;
}
.box2:first-letter{
font-size: 3em;
font-weight: bold;
}
.box2:first-line{
color: rgb(101, 245, 6);
}
</style>
</head>
<body>
<div class="wrap">
<div class="box1">
周末了,记得学习啊
</div>
<div class="box2">
复习一下css3
</div>
</div>
</body>
<script>
</script>
</html>
展现效果:
2) css3之后新增的伪元素
附上源码
<style>
.wrap{
height: auto;
width: 500px;
border: 1px rgb(5, 248, 114) solid;
padding: 10px;
display: flex;
flex-direction: column;
}
.box1:before{
content: "我是前面的before";
color: rgb(177, 81, 13);
}
.box1:after{
content: "我是后面的after";
color: rgb(243, 29, 72);
}
.box1{
background: rgb(221, 132, 214);
background-clip: content-box;
}
.box2:first-letter{
font-size: 3em;
font-weight: bold;
}
.box2:first-line{
color: rgb(101, 245, 6);
}
.box3::selection{
color:rgb(177, 81, 13);
}
.box4 input::placeholder{
color: #f00;
}
.box5{
display: flex;
flex-direction: row;
}
a{
text-decoration: none;
padding: 10px;
border-radius: 5px;
}
a.link:link{
background-color: rgb(203, 218, 151);
}
a.hover:visited{
background-color: rgb(221, 51, 142);
}
a.active:active{
font-size: 2em;
}
a.focus:focus{
background-color: rgb(247, 142, 4);
}
</style>
</head>
<body>
<div class="wrap">
<div class="box1">
周末了,记得学习啊
</div>
<div class="box2">
复习一下css3
</div>
<div class="box3">
这个是选中的内容的部分
</div>
<div class="box4">
<input type="text" placeholder="北京今天迎来了初雪啊">
</div>
<div class="box5">
<a class="link" href="#">正常链接</a>
<a class="visited" href="#">点击过后</a>
<a class="active" href="#">被激活时</a>
<a class="focus" href="#">获得焦点时</a>
</div>
</div>