css中伪类after before用法

:before 选择器在被选元素的内容后面插入内容。

:after 选择器在被选元素的内容后面插入内容。

1基本用法



    
        before和after
        
    
     
            

测试

输出结果:


2扩展用法

(1)

为边框添加边角

首先讲一下css的边框 border的构成

直接上代码和结果

代码:


    
        
        
    
     
        
   
   
结果:
这样就很清晰了,如果想要做一个三角,我们只需要把其它的边框设为透明就好了。
那如果我们想要div外边加三角怎么办呢,这时候就要用到before和after了


    
        
        
    
     
        
    
    
结果:

如果我们想要左边的三角只有框而不是填充满怎么办?这时候就要用after
<!DOCTYPE html >
< html >
< head >
< title ></ title >
< style >
.test{
margin-left: 500px;

position: relative;
width: 0px;
border-left: 50px solid red;
border-right: 50px solid green;
border-top: 50px solid yellow;
border-bottom: 50px solid black;
}
.test:before{
content: "";
position: absolute;
top: -50px;
left: -150px;
border: 50px solid transparent;
border-right: 50px solid blue;
}
.test:after{
content: "";
position: absolute;
top: -50px;
left: -146px;
z-index: 1;
border: 50px solid transparent;
border-right: 48px solid white;
}
< / style >
</ head >
< body >
< div class= "test" ></ div >
</ body >
</ html >


结果:



(2)作为透明背景

这里我做了一个有特效的button,尴尬的是不知道怎么做成动图传上来。。

代码:

<!DOCTYPE html >
< html >
< head >
< title ></ title >
< style >
.btn{
position: relative;
padding: 10px;
display: inline-block;
color: black;
border: 1px solid black;
-webkit-transition: all 0.5s; /*css3 过渡*/
transition: all 0.5s;
z-index: 1; /*图层堆叠顺序*/
}
.btn:after{
position: absolute;
top: 0px;
left: 0px;
width: 0%;
height: 100%;
content: "";
background: black;
-webkit-transition: all 0.5s; /*css3 过渡*/
transition: all 0.5s;
z-index: -1;
}
.btn:hover{
color: orange !important;
}
.btn:hover:after{
width: 100%;
background-color: black;
color: orange !important;
}
a{
text-decoration: none;
}
< / style >
</ head >
< body >
< div class= "test" >
< a href= "#" class= "btn" >这是一个按钮 </ a >
</ div >
</ body >
</ html >

这里把after的index设置的比btn的低,作为背景,然后将btn设置为相对布局,after为绝对布局(相对btn布局),当鼠标滑过触发hover事件时,

黑色背景色从左向右填充。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值