###############
boostrap中一段這樣的代碼:
*, *::before, *::after { box-sizing: border-box; }
咋一看按照 * {box-sizing: border-box} 這樣寫了不就將所有的元素都統一配置成box-sizing: border-box了嗎?爲何還多此一舉寫上*::before和*::after呢?
我們使用::before
僞元素添加了一個空字符串。我們已將其設置爲display: block
,以便我們可以使用寬度和高度對其進行樣式設置。然後我們使用 CSS 來設置它的樣式,就像任何元素一樣。您可以使用 CSS 並更改它的外觀和行爲方式
使用 ::before 和 ::after 生成內容
有幾個特殊的僞元素,它們與content
屬性一起使用,以使用 CSS 將內容插入到文檔中。這些僞元素也經常用於插入一個空字符串,然後可以像頁面上的任何元素一樣對其進行樣式設置。
您可以使用這些來插入一串文本,例如在下面的實時示例中。嘗試更改屬性的文本值content
並在輸出中查看它的變化。您還可以將::before
僞元素更改爲::after
並查看插入到元素末尾而不是開頭的文本。
然而,從 CSS 插入文本字符串並不是我們在網絡上經常做的事情,因爲某些屏幕閱讀器無法訪問該文本,並且將來可能很難有人找到和編輯。
這些僞元素更有效的用法是插入一個圖標,例如下面示例中添加的小箭頭,這是我們不希望屏幕閱讀器讀出的視覺指示器:
(1)舉例說明:無*::before和*::after
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>my css test</title> <style> * { box-sizing: border-box; } p { border: 20px solid red; padding: 20px; height: 200px; width: 400px; color: aqua; } .box::before { content: ""; display: block; width: 100px; height: 100px; background-color: rebeccapurple; border: 10px solid black; } </style> </head> <body> <p class="box" id="box">Content in the box in my HTML page.</p> </body> </html>
(2)舉例說明:有*::before和*::after
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>my css test</title> <style> *, *::before, *::after { box-sizing: border-box; } p { border: 20px solid red; padding: 20px; height: 200px; width: 400px; color: aqua; } .box::before { content: ""; display: block; width: 100px; height: 100px; background-color: rebeccapurple; border: 10px solid black; } </style> </head> <body> <p class="box" id="box">Content in the box in my HTML page.</p> </body> </html>
(3)也可改成如下這樣:
html { box-sizing : border-box ; } *,*::before,* ::after { box-sizing : inherit ; }
完整如下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>my css test</title> <style> html { box-sizing : border-box ; } *,*::before,* ::after { box-sizing : inherit ; } p { border: 20px solid red; padding: 20px; height: 200px; width: 400px; color: aqua; } .box::before { content: ""; display: block; width: 100px; height: 100px; background-color: rebeccapurple; border: 10px solid black; } </style> </head> <body> <p class="box" id="box">Content in the box in my HTML page.</p> </body> </html>
照理說*引起了所有的元素了,爲什麼和上面的html *::after *::before。
-
::after 和 ::before 的正式叫法是僞元素。
-
* 是所有的 DOM 樹中的元素,但 ::after 和 ::before 並不在文檔樹中。
在 CSS 中,使用::before
和::after
僞元素以及content
屬性被稱爲“生成的內容”,您經常會看到這種技術被用於各種任務。
一個很好的例子是網站CSS Arrow Please,它可以幫助您使用 CSS 生成箭頭。
在創建箭頭時查看 CSS,您將看到正在使用的::before
和::after
僞元素。每當您看到這些選擇器時,請查看content
屬性以查看添加到 HTML 元素中的內容。
###############