屬性選擇器
[att=val]
att代表屬性, val代表屬性值
//獲取id為section1的元素,并設(shè)置顏色為黃色
[id=section1]{
color : yellow;
}
[att*=val]
含義:如果元素用att表示的屬性的屬性值中包含用val指定的字符,則匹配該元素
//獲取id內(nèi)有box字符的元素,比如box,boxx,oboxsa
[id*=box]{
color : yellow
}
[att^=val]
含義:如果元素用att表示的屬性的屬性值的開頭字符為用val指定的字符,則匹配該元素
//獲取id內(nèi)以start開頭的元素,比如start1,start2
[id^=start]{
color : yellow
}
[att$=val]
含義:如果元素用att表示的屬性的屬性值的結(jié)尾字符為用val指定的字符,則匹配該元素
//獲取id以end結(jié)尾的元素,比如1end,2end
[id$=end]{
color : yellow
}
偽類選擇器
選擇器:偽元素{屬性 : 值}
first-line偽元素選擇器
用于為某個(gè)元素中的第一行文字使用樣式
//為該元素第一行文字設(shè)置顏色
p:first-line{
color : #0000ff;
}
first-letter偽元素選擇器
用于為某個(gè)元素中的文字的首字母或第一個(gè)字使用樣式
//為該元素第一個(gè)字符設(shè)置顏色
p:first-letter{
color : #0000ff;
before偽元素選擇器
before偽元素選擇器用于在某個(gè)元素之前插入一些內(nèi)容
//為每一個(gè)匹配的li元素之前加一個(gè)點(diǎn)
li:before{
content : *
}
after偽元素選擇器
after偽元素選擇器用于在某些元素之后插入一些內(nèi)容
//為所匹配的li元素后加內(nèi)容
li:after{
content : "鏈接",
font-size:12px;
color:red;
}
結(jié)構(gòu)性偽類選擇器
root, not, empty, target
root選擇器
root選擇器將樣式綁定到頁面的根元素中,即<html>
not選擇器
對某個(gè)結(jié)構(gòu)元素使用樣式,但又排除某個(gè)子結(jié)構(gòu)元素,可使用not選擇器
//排除h1元素
body *:not(h1){
color : yellow;
}
empty選擇器
使用empty選擇器來指定當(dāng)前元素為空白時(shí)使用
:empty{
background-color:yellow;
}
target
使用target選擇器來對頁面中某個(gè)target元素(該元素的id被當(dāng)作頁面中的超鏈接來使用)指定樣式,該樣式只在用戶點(diǎn)擊了頁面中的超鏈接,并且跳轉(zhuǎn)到target元素后起作用.
//錨鏈接,被選中的元素改變顏色
<a href="#text1">示例文字1</a>
<a href="#text2">示例文字2</a>
<a href="#text3">示例文字3</a>
<div id="text1">示例文字1</div>
<div id="text2">示例文字2</div>
<div id="text3">示例文字3</div>
div:target{
color : yellow;
}
first-child
匹配第一個(gè)子元素
li:first-child{
background-color : yellow;
}
last-child
匹配最后一個(gè)子元素
li:last-child{
background-color : yellow;
}
nth-child
匹配指定序列號子元素
//匹配第二個(gè)子元素
li:nth-child(2){
color : red
}
nth-last-child
匹配指定序列號子元素(倒數(shù))
//匹配倒數(shù)第二個(gè)子元素
li:nth-last-child(2){
color : yellow;
}
nth-child(odd)
對所有奇數(shù)序列子元素匹配
nth-child(even)
對所有偶數(shù)序列子元素匹配
nth-of-type
匹配指定序列號元素(同類元素)
//匹配第二個(gè)h2元素
h2:nth-of-type(2){
color : yellow;
}
nth-last-of-type
同上,不過倒著數(shù)
循環(huán)使用樣式
將n改為an+b即可, a表示每次循環(huán)包括幾種樣式, b表示指定的樣式在循環(huán)中的位置
li:nth-child(4n+1){
color ; yellow;
}
li:nth-child(4n+2){
color : red;
}
li:nth-child(4n+3){
color : pink;
}
li:nth-child(4n+4){
color : green;
}
only-child選擇器
匹配屬于父元素中唯一子元素的p元素
//匹配li唯一子元素
li:only-child{
color : red;
}
only-of-type選擇器
同理
UI元素狀態(tài)偽類選擇器
:hover
用來指定當(dāng)鼠標(biāo)指針移動(dòng)到元素上面時(shí)元素所使用的樣式
input[type="text"]:hover{
//指定的樣式
}
:focus
選擇器用來指定元素獲得光標(biāo)焦點(diǎn)時(shí)所使用的樣式,主要是在文本框控件獲得焦點(diǎn)并進(jìn)行文字輸入的時(shí)候使用
input[type="text"]:focus{
color : blue;
}