CSS-選擇器15-:before與:after

java小工匠發表於2017-08-12

CSS選擇器-系列文章

1、:before和:after偽元素

:before和:after,用於在修飾元素的內部最前端插入一個元素,或者最後段插入一個元素。

2、常見的應用

2.1 內容生成

原始碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>內容生成</title>
    <style type="text/css">
        p:before{
            content: `"`;
            color: red;
        }
        p:after{
            content: `"`;
            color: red;
        }
    </style>
</head>
<body>
    <p>這個一個p元素</p>
    <p>這個一個p元素</p>
    <p>這個一個p元素</p>
    <p>這個一個p元素</p>
    <p>這個一個p元素</p>
</body>
</html>

執行效果:
紅色的雙引號,是通過偽元素生成的。

內容生成

2.2 清除浮動的影響

原始碼:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>內容生成</title>
    <style type="text/css">
        .wrap{
            border: 1px solid red;
        }
        /*IE8必須用 *zoom:1;**/
        .wrap{*zoom:1;}
        .wrap:after{
            display:block; 
            content:""; 
            height:0; 
            clear:both; 
            overflow:hidden; 
            visibility:hidden;
        }
        .left{
            width: 100px;
            height: 100px;
            float: left;
            background: blue;
        }
    </style>
</head>
<body>
    <div class="wrap">
        <div class="left">
            
        </div>
    </div>
</body>
</html>

執行效果:

清楚浮動

2.3 讓大小不固定圖片垂直居中

原始碼:
素材圖片一張:

bg.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>內容生成</title>
    <style type="text/css">
        .wrap{
            width: 400px;
            height: 400px;
            border: 1px solid red;
            margin: 20px auto;
            font-size:0; 
            *font-size:300px; 
            text-align:center;
        }
        .wrap img{
            vertical-align: middle;
        }
        .wrap:after{
            display:inline-block; 
            width:0; 
            height:100%; 
            content:""; 
            vertical-align:middle; 
            overflow:hidden;
        }
    </style>
</head>
<body>
    <div class="wrap">
         ![](bg.png)
    </div>
</body>
</html>

執行效果:

image.png

CSS選擇器-系列文章


相關文章