伪元素::before和::after

  • ::before和::after 是什么?

   正解:伪元素~

   ...

   既然是一个严肃的技术博客,那就,严肃一点(正经脸)。

   ::after is a pseudo element which allows you to insert content onto a page from CSS (without it needing to be in the HTML).

   ::before is exactly the same only it inserts the content before any other content in the HTML instead of after. 

   ...

   ...

   ...

   还有人吗? 

   其实是这样的~

   

   有时候查看代码的时候,经常会看到在元素的中间有它们的身影,举个栗子。   

    <style type="text/css">
        .lizi{
            font-weight: bold;
            color: blue;
        }
        .lizi:after{
            content: "I'M after";
            color: #000;
        }
        .lizi:before{
            content: "I'M before";
            color: #000;
        }
    </style>
    <div class="lizi">
        I'M content~
    </div>

   

   所以,::before 就是以一个子元素的存在,定义在元素主体内容之前的一个伪元素。但是并不存在于dom中,只是显示在页面上而已。同理,after就是在主体内容之后显示的~

   

   那么,有些时候我们会看到的写法是:before 和:after, 那么,单冒号和双冒号的有区别吗?

   答案:肯定有啦,一个单身狗一对秀恩爱,瞎啊,肯定有区别。(掀桌)

      其实也就是浏览器的兼容性问题,最傲娇的是谁,肯定是IE啦。IE8不能识别双冒号,所以我们写的时候要友好的兼容它,一般采用单冒号。也就是和调用伪类的写法是一样的。

      你问IE8以下? 你撒啊? IE8都不兼容,它爷爷们能识别?

   

   (IE8下对伪元素不能设置z-index属性)

  • ::before和::after 常见的用法。

     在举栗子之前,看一下对于伪元素可以有怎样的设定。

  .lizi:after{
    content: "I'M after"; 			  /*插入字符串*/
    content: "attr(id)"; 			  /*插入当前元素属性*/
    content: url(/path/to/image.jpg);       /*插入图片*/
    content: counter(li); 			  /*插入计数器*/
    content: ""; 			          /*啥也不插*/
  }

  我知道你们要问计数器,等下再说 T T.

  下面列一下常用的用法

  • 清浮动

1 .clearfix:before,
2 .clearfix:after {
3     clear: both;
4     display: table;
5     content: "";
6 }
  • 字体图标

     栗子来自Bootstrap

     

     看着这朵花~它就是用伪元素的方法插入的。下面为代码

      

     

     字体图标的教程改天有空再来写吧,很实用的东西。

  • 插入符号(三角形)

     

      写了一个autocomplete的外框 

       附上一个使用border画三角形的教程 http://www.jb51.net/article/42513.htm

 1     <div class="triangle">
 2         <input type="text">
 3     </div>
 4     <style type="text/css">
 5         .triangle input{
 6             height: 30px;
 7             width: 200px;
 8             border-radius: 4px;
 9             border: 1px solid #ccc;
10         }
11         .triangle{
12             width: 200px;
13             position: relative;
14         }
15         .triangle:after{
16             position: absolute;
17             top: 12px;
18             right: 5px;
19             content: "";
20             width: 0;
21             height: 0;
22             border: 8px solid transparent;
23             border-top-color: red;
24         }
25     </style>                
  • 计数

     允许我偷个懒

     http://www.qianduan.net/css-content-counter-increment-counter-reset/

     写的很详细。

 

原文地址:https://www.cnblogs.com/ellenwu/p/4939963.html