7-7 CSS3选择器 ::before和::after
本节编程练习不计算学习进度,请电脑登录imooc.com操作

CSS3选择器 ::before和::after

::before和::after这两个主要用来给元素的前面或后面插入内容,这两个常和"content"配合使用,使用的场景最多的就是清除浮动。

.clearfix::before,
.clearfix::after {
    content: ".";
    display: block;
    height: 0;
    visibility: hidden;
}
.clearfix:after {clear: both;}
.clearfix {zoom: 1;}


当然可以利用他们制作出其他更好的效果,比如右侧中的阴影效果,也是通过这个来实现的。

关键代码分析:

.effect::before, .effect::after{
    content:"";
    position:absolute;
    z-index:-1;
    -webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
    -moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
    box-shadow:0 0 20px rgba(0,0,0,0.8);
    top:50%;
    bottom:0;
    left:10px;
    right:10px;
    -moz-border-radius:100px / 10px;
    border-radius:100px / 10px;
}

上面代码作用在class名叫.effect上的div的(before)(after)都添加一个空元素,然后为这两个空元素添加阴影特效。

想看这个知识点深入讲解的小伙伴请观看《css3实现图片阴影效果》中的第1-6小节

任务

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset=utf-8 />
  5. <title>before、after</title>
  6. <style>
  7. .box h3{
  8. text-align:center;
  9. position:relative;
  10. top:80px;
  11. }
  12. .box {
  13. width:70%;
  14. height:200px;
  15. background:#FFF;
  16. margin:40px auto;
  17. }
  18.  
  19. .effect{
  20. position:relative;
  21. -webkit-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
  22. -moz-box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
  23. box-shadow:0 1px 4px rgba(0, 0, 0, 0.3), 0 0 40px rgba(0, 0, 0, 0.1) inset;
  24. }
  25. .effect::before, .effect::after{
  26. content:"";
  27. position:absolute;
  28. z-index:-1;
  29. -webkit-box-shadow:0 0 20px rgba(0,0,0,0.8);
  30. -moz-box-shadow:0 0 20px rgba(0,0,0,0.8);
  31. box-shadow:0 0 20px rgba(0,0,0,0.8);
  32. top:50%;
  33. bottom:0;
  34. left:10px;
  35. right:10px;
  36. -moz-border-radius:100px / 10px;
  37. border-radius:100px / 10px;
  38. }
  39. </style>
  40. </head>
  41. <body>
  42. <div class="box effect">
  43. <h3>Shadow Effect </h3>
  44. </div>
  45. </body>
  46. </html>
下一节