偽元素before和after用法總結


常見偽元素:

常見偽元素——::first-letter,::first-line,::before,::after,::selection。

​ 其中::before和::after常用在項目中,巧妙的運用會會使很多樣式的實現變得非常簡單.

​ 一般地,我們不去用::before和::after展示實際性的頁面內容,多是修飾性的,像icon,角標,行標,還可以配合content清除浮動.

::before顯示電話前的電話機icon:
這里寫圖片描述

    <style type="text/css"> .phoneNumber::before { content:'\260E'; font-size: 15px; } </style>
</head>

<body>
    <p class="phoneNumber">12345645654</p>
</body>

content屬性:

​ ::before和::after必須配合content屬性來使用,content用來定義插入的內容 ,content可取以下值。

1 ) string

引號括起來的一段字符串,顯示到當前元素的前后:

p::before{
    content: "《";
}
p::after{
    content: "》";
}
<p>平凡的世界</p>
//效果《平凡的世界》

2 ) attr()

通過attr()調用當前元素的屬性,比如將圖片alt提示文字或者鏈接的href地址顯示出來。

<style> a::after{ content: "(" attr(href) ")"; } </style>
<a href="http://www.csdn.com/starof">博客地址</a>
//效果    博客地址(http://www.csdn.com/starof)

3 ) url()/uri()

用於引用媒體文件。

舉例:“百度”前面給出一張圖片,后面給出href屬性。

<style> a::before{ content: url("https://www.baidu.com/img/baidu_jgylogo3.gif"); } a::after{ content:"("attr(href)")"; } a{ text-decoration: none; } </style>
---------------------------
<body>
<a href="http://www.baidu.com">百度</a>
</body>  

這里寫圖片描述
這里寫圖片描述### 4 ) counter()

調用計數器,實現章節序號功能。

<style> body { counter-reset: section; } h1 { counter-reset: subsection; } h2 { counter-reset: subsection; } h1:before { counter-increment: section; content: counter(section) "、"; } h2:before { counter-increment: subsection; content: counter(section) "." counter(subsection) "、"; } h3:before { counter-increment: subsection; content: counter(section) "." counter(section) "."counter(subsection) "、"; } </style>
</head>

<body>
    <h1>大標題</h1>
    <h2>&emsp;二副</h2>
    <h2>&emsp;二副</h2>
    <h2>&emsp;二副</h2>
    <h3>&emsp;&emsp;三副</h3>
    <h3>&emsp;&emsp;三副</h3>
    <h3>&emsp;&emsp;三副</h3>
</body>

這里寫圖片描述

運用

1、清除浮動

清除浮動方法有多種,現在最常用的就是下面這種方法,僅需要以下樣式即可在元素尾部自動清除浮動

.cf:before,
.cf:after { content: " "; display: table; }
.cf:after { clear: both; }
.cf { *zoom: 1; }

2、float:居中

我們知道float沒有center這個取值,但是可以通過偽類來模擬實現。

這個效果實現很有意思,左右通過::before float各自留出一半圖片的位置,再把圖片絕對定位上去。

3、做出各種圖形效果

案例:六芒星

div做成三角形,將::after做成倒三角,絕對定位到div上

       #star-six { width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-bottom: 100px solid red; position: relative; }
       #star-six::after{ width: 0; height: 0; border-left: 50px solid transparent; border-right: 50px solid transparent; border-top: 100px solid red; position: absolute; content: ""; top: 30px; left: -50px; }

這里寫圖片描述
這里寫圖片描述
不了解CSS繪制圖形的點這里→Shape of CSS

4、超鏈接特效

舉例:配合 CSS定位實現一個鼠標移上去,超鏈接出現方括號的效果

a:hover::before, a:hover::after { position: absolute; }
a:hover::before { content: "\5B"; left: -10px; }
a:hover::after { content: "\5D"; right: -10px; }

這里寫圖片描述

常見的偽元素用法就說這么多,另外
附上一個有趣的連接:使用CSS3實現各類圖形,效果滿分


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM