6.1 屬性 content
偽元素 ::before
和 ::after
允許你在元素內容之前和之後添加內容,而不改變 HTML 代碼。
它們廣泛用於裝飾目的、改進用戶界面和創建更具互動性的網頁。
什麼是偽元素 ::before 和 ::after?
偽元素 ::before
和 ::after
創建虛擬元素,它們分別插入在選定元素的內容之前和之後。
這些偽元素經常用於添加圖標、裝飾元素或其他視覺效果。
before 的語法:
選擇器::before {
content: "文本或其他值";
/* 樣式 */
}
after 的語法:
選擇器::after {
content: "文本或其他值";
/* 樣式 */
}
屬性 content
對於偽元素 ::before
和 ::after
,關鍵屬性是 content
。這個屬性定義了偽元素的內容。
它可以是一個文本字符串、圖片、甚至是空值,如果只需要視覺效果的話。
屬性 content 的可能值:
- 文本:
"文本"
- 圖片:
url("path/to/image.png")
- 空值:
""
- 屬性:
attr(attributeName)
- 計數器:
counter(name)
6.2 使用 ::before 和 ::after 的範例
添加裝飾元素
範例 1:在文本前添加圖標
在這個範例中,偽元素 ::before
用於在鏈接文本前添加圖標。
margin-right
在圖標和文本之間添加空間:
/* 在鏈接文本前添加圖標 */
a::before {
content: "🔗";
margin-right: 5px;
}
範例 2:在段落後添加裝飾元素
在這個範例中,偽元素 ::after
在段落後添加裝飾元素。display: block
和
text-align: right
用於將元素對齊右側:
/* 在段落後添加裝飾元素 */
p::after {
content: "❦";
display: block;
text-align: right;
color: red;
}
創建裝飾框和背景
範例 3:元素周圍的裝飾框
在這個範例中,偽元素 ::before
用於創建元素 div
上方的裝飾條。
position: absolute
和 top: -10px
允許將條置於元素上方:
/* 元素周圍的裝飾框 */
div::before {
content: "";
display: block;
width: 100%;
height: 10px;
background-color: #3498db;
position: absolute;
top: -10px;
left: 0;
}
範例 4:自動添加引號
在這個範例中,偽元素 ::before
和 ::after
用於在引用塊周圍添加引號:
/* 在引用周圍自動添加引號 */
blockquote::before {
content: "“";
font-size: 2em;
color: #ccc;
}
blockquote::after {
content: "”";
font-size: 2em;
color: #ccc;
}
範例 5:標題編號
在這個範例中,偽元素 ::before
用於在 h2
標題前添加編號。
counter-increment
增加計數器的值,而 content: counter(section)
插入當前計數器的值:
/* 標題編號 */
h2::before {
counter-increment: section;
content: counter(section) ". ";
font-weight: bold;
}
6.3 偽元素的應用和樣式化
偽元素的樣式化
偽元素可以像其他元素一樣進行樣式化。它們支持大多數 CSS 屬性,包括顏色、背景、邊框、大小和定位。
使用偽元素創建複雜的佈局
偽元素經常用於在佈局中創建裝飾元素,比如框、陰影和其他視覺效果,而無需添加額外的 HTML 元素。
範例:每個列表項前都將有一個藍色標記:
ul li::before {
content: "•";
color: blue;
margin-right: 5px;
}
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
6.4 完整實現範例
/* 在鏈接文本前添加圖標 */
a::before {
content: "🔗";
margin-right: 5px;
}
/* 在段落後添加裝飾元素 */
p::after {
content: "❦";
display: block;
text-align: right;
color: red;
}
/* 元素周圍的裝飾框 */
.decorative-box {
position: relative;
}
.decorative-box::before {
content: "";
display: block;
width: 100%;
height: 10px;
background-color: #3498db;
position: absolute;
top: -10px;
left: 0;
}
/* 在引用周圍自動添加引號 */
blockquote::before {
content: "“";
font-size: 2em;
color: #ccc;
}
blockquote::after {
content: "”";
font-size: 2em;
color: #ccc;
}
/* 標題編號 */
h2::before {
counter-increment: section;
content: counter(section) ". ";
font-weight: bold;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>偽元素 ::before 和 ::after 的範例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<a href="#">帶圖標的連結</a>
<p>段落後的裝飾元素</p>
<div class="decorative-box">帶裝飾框的元素</div>
<blockquote>帶自動引號的引用</blockquote>
<h2>帶編號的標題</h2>
<h2>另一個標題</h2>
</body>
</html>
GO TO FULL VERSION