預定義
/* 這里預定義幾個變量(自定義屬性),方便后面使用 */
:root {
--green: #1dd1a1;
--red: #ff7979;
--blue: #7ed6df;
--yellow: #f9ca24;
--border: 1px solid #666;
}
/* 預定義一個選擇器 */
div {
float: left;
margin-left: 10px;
width: 100px;
height: 50px;
border: var(--border);
background-color: var(--green);
}
:root
:root
匹配元素所在文檔的根元素。在HTML文檔中,根元素始終是<html>
。
:root {
background-color: var(--blue);
}
<body><!-- 什么都沒寫 --></body>
:empty
:empty
選擇沒有任何內容的元素(有空格也不行)。
div:empty {
background-color: var(--red);
}
<div> </div>
<div>1231</div>
<div>abc</div>
<div>*()_</div>
<div>...</div>
<div></div>
:target
:target
表示一個唯一的元素(目標元素),其ID與URL的片段匹配。
#first:target {
background-color: var(--red);
}
#second:target {
background-color: var(--blue);
}
#third:target {
background-color: var(--yellow);
}
<a href="#first">first</a>
<a href="#second">second</a>
<a href="#third">third</a>
<div id="first"></div>
<div id="second"></div>
<div id="third"></div>
:first-child
:first-child
選擇元素中的第一個子元素。
div:first-child {
background-color: var(--red);
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
:last-child
:last-child
選擇元素的最后一個子元素。
div:last-child {
background-color: var(--red);
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
:nth-child(n)
:nth-child(n)
定位某個父元素的一個或多個特定的子元素。其中 n 是其參數。n 取值如下:
1.整數值(1 || 2 || 3 || 4 || ...)
參數n的起始值為1,不是0,若要選中第一個元素nth-child(1)
。
2.表達式(2n+1 || -n+5 || ...)
為表達式時,n從0開始,表達式的值為0或小於0的時,不選擇任何匹配的元素。
3.關鍵詞(odd || even)
odd
和 even
是可用於匹配下標是奇數(odd)或偶數(even)的子元素的關鍵詞(第一個子素的下標是 1)。
div:nth-child(2n) {
background-color: var(--red);
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
:nth-last-child(n)
:nth-last-child(n)
從某父元素的最后一個子元素開始選擇特定的元素。n取值同nth-child(n)的n取值。
div:nth-last-child(2n) {
background-color: var(--red);
}
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
:not
:not
選擇除某個元素之外的所有元素。
div {
float: left;
margin-left: 10px;
width: 100px;
height: 50px;
border: var(--border);
background-color: var(--green);
}
div:not(.item) {
background-color: var(--red);
}
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="diff"></div>
<div class="item"></div>
:not 可以配合其他選擇器使用,例如:
div:not(:first-child){....}
。