一、介绍
::before和::after是伪元素,(css3中为了与伪类做区别,伪元素采用双冒号的写法;但因为兼容性的问题,所以现在大部分还是统一的单冒号,比如:first-line、:first-letter、:before、:after等,但新的在CSS3中引入的伪元素就不允许用单冒号的写法。)
“:before” 伪元素可以在元素的内容前面插入新内容。 “:after” 伪元素可以在元素的内容之后插入新内容。
::before或::after都必须和content属性结合使用,content不能没有,内容至少为空;伪元素的display默认为inline,可以自己改.
二、用法
1.利用content的值: (1)content:“字符串”;
可以统一在字前面或后面加一些字符 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200312223042358.png)
p:after{~~删除线格式~~
content:":";
}
请输入姓名
请输入年龄
请输入性别
(2)content:url(…)
可以在字前面加一些小的图标,通过定位把位置调合适 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200312224621705.png)
p::before{
content:url(footer3.png);
position: relative;
top:17px;
}
微信
(3)通过attr()属性调用当元素的属性,比如将图片alt提示文字或者链接的href地址显示出来。
attr() 函数返回选择元素的属性值。 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200314110309335.png)
a::after{
content:"(" attr(href) ")";
}
p:after{
content:attr(class);
}
微信
2.实现三角形 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200314124445923.png)
#top-triangle{
width:0px;
height:0px;
border:20px solid transparent;
border-bottom:20px solid pink;
}
#right-triangle{
width:0px;
height:0px;
border:20px solid transparent;
border-left:20px solid pink;
}
#bottom-triangle{
width:0px;
height:0px;
border:20px solid transparent;
border-top:20px solid pink;
}
#left-triangle{
width:0px;
height:0px;
border:20px solid transparent;
border-right:20px solid pink;
}
3.实现对话框效果: ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200314145621147.png)
.left,.right{
position: relative; /*后面移动会盒子位置*/
display: table;
min-height: 40px;
text-align: center;
background-color: #9EEA6A;
margin: 0;
border-radius: 7px;
}
.left{
left:10px;
}
.left::before,.right::after{
position: absolute;
display: inline-block;
content: "";
width: 0px;
height: 0px;
border: 8px solid transparent;
top: 15px; /*移到中间*/
}
.left::before{
border-right-color: #9EEA6A;
left: -16px;
}
.right::after{
border-left-color: #9EEA6A;
right: -16px;
}
.left p,.right p{
padding:0px 10px;
}
.right{
right:-150px;
}
你好啊
好久不见~
4.实现箭头 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20200314152101957.png)
.box{
position: relative;
width: 200px;
height: 50px;
background-color: pink;
}
.box::before{
position: absolute;
content:"";
width: 12px;
height: 12px;
border: 1px solid black;
border-bottom-color: transparent;
border-right-color: transparent;
transform: translate(-50%, -50%) rotate(-45deg);
left: 20px;
top: 50%;
}
5.清除浮动 原理:利用:after和:before在元素内部插入两个元素块,从而达到清除浮动的效果。
.outer:after {
clear:both; /*清除浮动*/
content:'';
display:block; /*显示伪元素*/
width:0;
height:0; /*不占位置*/
visibility:hidden; /*允许浏览器渲染它,但是不显示出来*/
}
6.画分割线:画一条分割线 ![在这里插入图片描述](https://img-blog.csdnimg.cn/20210216113608829.png)
* {
padding: 0;
margin: 0;
}
.spliter::before, .spliter::after {
content: '';
display: inline-block;
border-top: 1px solid black;
width: 200px;
margin: 5px;
}
分割线
|