zoukankan      html  css  js  c++  java
  • 【转载】CSS 伪类-:before和:after

    :before和:after的作用就是在指定的元素内容(而不是元素本身)之前或者之后插入一个包含content属性指定内容的行内元素,最基本的用法如下:

    #example:before {
        content: "#";
        color: red;
    }
    
    #example:after {
        content: "$";
        color: red;
    }
    

    这段代码会在#example元素内容之前插入一个'#',以及在内容之后添加一个'$',插入的行内元素是作为#example的子元素,效果如下:

    Here is the example content

    需要注意的是如果没有content属性,伪类元素将没有任何作用。但是可以指定content为空,同时正如前面所说,插入的内容默认是一个行内元素,并且在HTML源代码中无法看到,这就是为什么称之为伪类元素的理由,所以也就无法通过DOM对其进行操作。

    #example:before {
        content: "";
        display: block;
         100px;
        height: 100px;
    }
    

    伪类元素也会像其他子元素一样正常继承父元素的一些CSS属性,比如字体等。

    除了插入文字内容,还可以指定其他内容:

    p:before {
        content: url('img.jpg');
    }
    a:after {
        content: attr(href);
    }
    

    attr()函数会返回指定元素对应属性的值

    最后,奉上最惦记的浏览器支持情况

    • Chrome 2+,
    • Firefox 3.5+ (3.0 had partial support),
    • Safari 1.3+,
    • Opera 9.2+,
    • IE8+ (with some minor bugs),
    • Pretty much all mobile browsers.

    放在伪类元素里面的内容一般都只是装饰性的,所以即便是IE6/7不支持也应该能降级到正常显示主体内容。

    :before和:after的一些惊人用法

    >. clearfix hack

    如果父元素容器里面的子元素是浮动元素的话,我们一般需要在父元素闭合前添加一个clear:both的元素用于清除浮动从而能使父容器正常被子元素内容撑起,但是这种方法引入了多余的无意义标签,并且有javascript操作子元素的时候容易引发bug。一种更好的方法是利用CSS,所以在一些CSS文件中经常会看到类似于.clearfix这样的类出没,只要在父容器上应用这个类即可实现清除浮动。下面是利用:before和:after的一个实现:(via Nicolas Gallagher)

    /* For modern browsers */
    .clearfix:before,
    .clearfix:after {
        content:"";
        display:table;
    }
    
    .clearfix:after {
        clear:both;
    }
    
    /* For IE 6/7 (trigger hasLayout) */
    .clearfix {
        zoom:1;
    }
    

    >. CSS实现的八卦图案

    #yin-yang {
         96px;
        height: 48px;
        background: #eee;
        border-color: red;
        border-style: solid;
        border- 2px 2px 50px 2px;
        border-radius: 100%;
        position: relative;
    }
    
    #yin-yang:before {
        content: "";
        position: absolute;
        top: 50%;
        left: 0;
        background: #eee;
        border: 18px solid red;
        border-radius: 100%;
         12px;
        height: 12px;
    }
    
    #yin-yang:after {
        content: "";
        position: absolute;
        top: 50%;
        left: 50%;
        background: red;
        border: 18px solid #eee;
        border-radius:100%;
         12px;
        height: 12px;
    }
    

    【原文】http://www.hulufei.com/post/about-before-and-after-pseudo-element
  • 相关阅读:
    poj 1753 Flip Game
    SDIBT 2345 (3.2.1 Factorials 阶乘)
    HDU 1176 免费馅饼
    HDU 1058 Humble Numbers
    HDU 1003 MAXSUM(最大子序列和)
    HDU1864 最大报销额
    HDU 1114 Piggy-Bank(完全背包)
    POJ 3624 Charm Bracelet
    处理textarea里Enter(回车换行符)
    uniApp打卡日历
  • 原文地址:https://www.cnblogs.com/yingsong/p/6066760.html
Copyright © 2011-2022 走看看