css中伪类after before用法

来源:互联网 发布:电脑编程入门自学黑客 编辑:程序博客网 时间:2024/06/10 07:15

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

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

1基本用法

            before和after                    p:before{                content: "before";            }            p:after{                content: "after";            }                             

测试

输出结果:


2扩展用法

(1)

为边框添加边角

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

直接上代码和结果

代码:
                                .test{                width: 0px;                border-left: 50px solid red;                border-right: 50px solid green;                border-top:50px solid yellow;                border-bottom: 50px solid black;            }                         
结果:
这样就很清晰了,如果想要做一个三角,我们只需要把其它的边框设为透明就好了。
那如果我们想要div外边加三角怎么办呢,这时候就要用到before和after了
                                .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;            }                         
结果:

如果我们想要左边的三角只有框而不是填充满怎么办?这时候就要用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:50pxsolid yellow;
border-bottom: 50px solid black;
}
.test:before{
content: "";
position: absolute;
top:-50px;
left: -150px;
border:50pxsolid transparent;
border-right: 50px solid blue;
}
.test:after{
content: "";
position: absolute;
top:-50px;
left: -146px;
z-index: 1;
border:50pxsolid 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: 1pxsolid black;
-webkit-transition: all 0.5s; /*css3 过渡*/
transition: all0.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: all0.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事件时,

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

原创粉丝点击