结合之前CSS中的z-index属性的介绍,这篇将层叠性扩展到伪元素。
伪元素:设置在对象前(依据DOM树的逻辑结构)发生的内容。用来和content属性一起使用,并且必须定义content属性。
通过改变伪元素和元素盒子的z-index来确定其中的层叠关系
<div>
<p class="a">aaaaaaaaaa</p>
</div>
1. .a {
2. background-color: pink;
3. }
4. .a::before {
5. content: "";
6. background-color: yellow;
7. width: 100px;
8. height: 100px;
9. position: absolute;
10. top: 20px;
11. left: 20px;
}
1、都不设置z-index的情况下:
伪元素默认是在元素的前面添加的,所以在整个盒子的上面。可以等价于设置 :
div:z-index:0;伪元素:z-index:1;
2、改变z-index参数
div:z-index:0;
伪元素:z-index:-1;
3、改变z-index参数
div:不设置
伪元素:z-index:-1;
根据上述三种设置,可以看出盒子内容(文字)和盒子本身之间是有层次的。可以理解为div这里设置z-index只改变了盒子内容的层级。
结合知识点的例题:实现按钮的滑动效果
1. <!DOCTYPE html>
2. <html lang="en">
3. <head>
4. <meta charset="UTF-8">
5. <title>实现滑动效果</title>
6. <style type="text/css">
7. a {
8. text-decoration: none;
9. }
10. .sub {
11. display: inline-block;
12. width: 416px;
13. height: 60px;
14. line-height: 60px;
15. background: #3b5998 url("images/fb.png") no-repeat 57px 16px ;
16. background-color: #3b5998;
17. color: #fff;
18. font-size: 20px;
19. text-align: center;
20. border-radius: 5px;
21. position: relative;
22. /*指的是元素的层级*/
23. z-index: 0;
24. /*实现效果相同*/
25. transform:translateZ(0);
26.
27. }
28. .sub::before {
29. /*伪元素,是在盒子元素的前面*/
30. content: "";
31. width: 416px;
32. height: 60px;
33. z-index: -1;
34. border-radius: 5px;
35. position: absolute;
36. left: 0;
37. background:#354d7d;
38. transform: scaleX(0);
39. transform-origin: 0 50%;
40. transition-property: transform;
41. transition-duration: 0.3s;
42. transition-timing-function: ease-out;
43. }
44. .sub:hover:before {
45. transform:scaleX(1);
46. }
47. </style>
48. </head>
49. <body>
50. <a href="#" class="sub">
51. Sign in with Facebook
52. </a>
53. </body>
54. </html>
实现结果:(这就是之前说的按钮滑动的效果)