CSS偽類
::before/ after
在一個元素標簽的前面或者后面, 創建一個新的虛擬的標簽, 我們可以給這個虛擬的標簽增加樣式, 也可以增加內容等...
.box p::before {
display: block;
height: 30px;
line-height: 30px;
text-align: center;
content: "lemon before";
background: lightblue;
}
.box p::after {
display: block;
height: 30px;
line-height: 30px;
text-align: center;
content: "lemon after";
background: lightgreen;
}
::nth-child(n)
匹配屬於其父類的第N個子元素, 不論元素的類型, n可以是數字, 關鍵詞或公式
.list li:nth-child(4n + 1) {
background-color: yellowgreen;
}
.list li:nth-child(4n + 2) {
background-color: lightskyblue;
}
.list li:nth-child(4n + 3) {
background-color: lightsalmon;
}
.list li:nth-child(4n + 4) {
background-color: lightslategrey;
}
清除浮動
.clear {
zoom: 1;
}
.clear::after {
display: block;
width: 0;
height: 0;
content: "";
overflow: hidden;
clear: both;
}
獲取偽類樣式
var boxP = document.getElementById("boxP");
console.log(window.getComputedStyle(boxP, "before").content);
"lemon before"
整個HTML文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
#box {
margin: 100px;
padding: 30px;
width: 200px;
height: 200px;
border: 10px solid green;
}
.box p {
line-height: 30px;
}
.box p::before {
display: block;
height: 30px;
line-height: 30px;
text-align: center;
content: "lemon before";
background: lightblue;
}
.box p::after {
display: block;
height: 30px;
line-height: 30px;
text-align: center;
content: "lemon after";
background: lightgreen;
}
.clear {
zoom: 1;
}
.clear::after {
display: block;
width: 0;
height: 0;
content: "";
overflow: hidden;
clear: both;
}
.list {
width: 300px;
margin: 20px auto;
padding: 20px;
border: 1px solid;
}
.list li {
float: left;
width: 100px;
height: 100px;
}
/* .list li:nth-child(odd) {
background-color: yellowgreen;
}
.list li:nth-child(even) {
background-color: lightskyblue;
} */
.list li:nth-child(4n + 1) {
background-color: yellowgreen;
}
.list li:nth-child(4n + 2) {
background-color: lightskyblue;
}
.list li:nth-child(4n + 3) {
background-color: lightsalmon;
}
.list li:nth-child(4n + 4) {
background-color: lightslategrey;
}
ul,
li {
list-style: none;
}
</style>
<body>
<div class="box">
<p id="boxP">
要得到你必須要付出,要付出你還要學會堅持,如果你真的覺得很難,那你就放棄,但是你放棄了就不要抱怨,我覺得人生就是這樣,世界是公平的,每個人都是通過自己的努力,去決定自己生活的樣子
</p>
</div>
<ul class="list clear">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<script>
var boxP = document.getElementById("boxP");
console.log(window.getComputedStyle(boxP, "before").content);
</script>
</html>