CSS 中的 ::before 和 ::after 偽元素
CSS ::before 和 CSS ::after 偽元素用於在元素前後分別插入一些內容。
::after 偽元素
如果你想在元素後插入內容,則使用 ::after 偽元素。使用內容屬性設定要放置在後面的內容 -
p::after {
content: " is Virat Kohli";
background-color: red;
font-weight: bold;
}
範例
讓我們看一個例子 -
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: blue;
color: white;
}
p::after {
content: " is Virat Kohli";
background-color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Cricket is love</h1>
<p>Favourite Cricketer</p>
<p>Favourite Batsman</p>
</body>
</html>
::before 偽元素
如果你想在元素前插入內容,則使用 ::before 偽元素。使用內容屬性設定要放置在後面的內容 -
p::before {
content: "Virat Kohli:";
background-color: red;
font-weight: bold;
}
範例
讓我們看一個例子 -
<!DOCTYPE html>
<html>
<head>
<style>
p {
background-color: blue;
color: white;
}
p::before {
content: "Virat Kohli:";
background-color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Cricket is love</h1>
<p>Favourite Cricketer</p>
<p>Favourite Batsman</p>
</body>
</html>
範例
讓我們看一個 CSS ::before 和 CSS ::after 偽元素的示例 -
<!DOCTYPE html>
<html>
<head>
<style>
div:nth-of-type(1) p:nth-child(2)::after {
content: " BUZZINGA!";
background: orange;
padding: 5px;
}
div:nth-of-type(2) p:nth-child(2)::before {
content: "Harry:";
background-color: lightblue;
font-weight: bold;
padding: 5px;
}
</style>
</head>
<body>
<div>
<p>Nobody: </p>
<p>Sheldon Cooper:</p>
</div><hr>
<div>
<p><q>Death Eaters arrive</q></p>
<p><q>Expecto Patronum!</q></p>
</div>
</body>
</html>
範例
讓我們看另一個 CSS ::before 和 CSS ::after 偽元素的示例 -
<!DOCTYPE html>
<html>
<head>
<title>Center Alignment using CSS Margin</title>
<style>
#yinyangSymbol {
width: 100px;
height: 50px;
background: #fff;
border-color: #000;
border-style: solid;
border-width: 2px 2px 50px 2px;
border-radius: 100%;
position: relative;
}
#yinyangSymbol::before {
content: "";
position: absolute;
top: 50%;
left: 0;
background: #fff;
border: 18px solid #000;
border-radius: 100%;
width: 14px;
height: 14px;
}
#yinyangSymbol::after {
content: "";
position: absolute;
top: 50%;
left: 50%;
background: #000;
border: 18px solid #fff;
border-radius:100%;
width: 14px;
height: 14px;
}
div{
width: 50%;
margin: 10px auto;
border:4px solid black;
}
#text {
border: 4px solid black;
background-color: grey;
color: white;
text-align: center;
}
</style>
</head>
<body>
<div id="main">
<div>
<div id="yinyangSymbol"></div>
</div>
<div id="text">Be Centered & Balanced</div>
</div>
</body>
</html>
廣告
資料結構
計算機網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
JavaScript
PHP