JavaScript前端中的偽類元素before和after使用詳解
目錄
- 1.基本用法
- 2.樣式修改
- 3.清除浮動
- 4.content屬性
- 1、string
- 2、attr()
- 3、url()/uri()
- 4、counter()
before/after
偽類相當于在元素內部插入兩個額外的標簽,其最適合也是最推薦的應用就是圖形生成。在一些精致的UI實現上,可以簡化HTML代碼,提高可讀性和可維護性。
效果使用:
像這種小圖標大多使用before,after來實現,不僅簡單還方便。
1.基本用法
:before和:after的作用就是在指定的元素內容(而不是元素本身)之前或者之后插入一個包含content屬性指定內容的行內元素,最基本的用法如下:
#example:before { content: "#"; color: red;}#example:after { content: "$"; color: red;}
這兩個偽類都屬于內聯元素,但是用display:block;屬性可以將其轉換成塊狀元素,比較常見的用法就是樣式的一些實現,還有就是清除浮動的效果。。
2.樣式修改
代碼如下所示:
<div> <span>打老虎</span></div>.quote:before,.quote:after{//用這兩個偽類實現樣式渲染 content:""; display:inline-block; width:5%; margin:5px 1%; border-bottom:1px solid blue;}
3.清除浮動
代碼如下所示:
<div> <div></div> <div></div></div><div>parent2</div>//css代碼.son1{ width:300px; height:200px; background-color: lightgray; float:left;}.son2{ width:300px; height:100px; background-color: lightblue; float:left;}.parent2{ width:400px; height: 400px; background-color:blue; color:#fff; text-align:center; line-height:400px; font-size:30px;}
如果在上面代碼中加上這段代碼用來清除浮動則會達到不一樣的效果:
.parent:after{ content:""; display:block;//設為塊狀元素 clear:both; //用這個屬性來清除浮動}
::before和::after下特有的content,用于在css渲染中向元素邏輯上的頭部或尾部添加內容。
這些添加不會出現在DOM中,不會改變文檔內容,不可復制,僅僅是在css渲染層加入。
所以不要用:before或:after展示有實際意義的內容,盡量使用它們顯示修飾性內容,例如圖標。
注意:在使用before和after時content必不可少。
注意:在使用before和after時content必不可少。
注意:在使用before和after時content必不可少。
4.content屬性
::before和::after必須配合content屬性來使用,content用來定義插入的內容,content必須有值,至少是空。默認情況下,偽類元素的display是默認值inline,可以通過設置display:block來改變其顯示。
content可取以下值。
1、string
使用引號包一段字符串,將會向元素內容中添加字符串。如:a:after{content:""}
<!DOCTYPE html><meta charset="utf-8" /><style type="text/css">p::before{ content: "《"; color: blue;}p::after{ content: "》"; color: blue;}</style><p>平凡的世界</p>
2、attr()
通過attr()調用當前元素的屬性,比如將圖片alt提示文字或者鏈接的href地址顯示出來。
<style type="text/css">a::after{ content: "(" attr(href) ")";}</style><a rel="external nofollow" >starof</a>
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 rel="external nofollow" >百度</a></body>
4、counter()
調用計數器,可以不使用列表元素實現序號功能。
配合counter-increment和counter-reset屬性使用:
h2:before { counter-increment: chapter; content: "Chapter " counter(chapter) ". " }
<style>body{ counter-reset: section;}h1{ counter-reset: subsection;}h1:before{ counter-increment:section; content:counter(section) "、";}h2:before{ counter-increment:subsection; content: counter(section) "." counter(subsection) "、";}</style>------------------------------------------------<body><h1>HTML tutorials</h1><h2>HTML Tutorial</h2><h2>XHTML Tutorial</h2><h2>CSS Tutorial</h2><h1>Scripting tutorials</h1><h2>JavaScript</h2><h2>VBScript</h2><h1>XML tutorials</h1><h2>XML</h2><h2>XSL</h2></body>
到此這篇關于JavaScript前端中的偽類元素before和after使用詳解的文章就介紹到這了,更多相關JS before和after內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!