菜鳥救星網頁設計教學:一次搞懂CSS3選擇器

文、菜鳥編
CSS除了id,class選擇器外,你還知道有哪些?其實在CSS3的規範之下,還有許多相當好用的選擇器可提升開發靈活性。如果你還不是很了解,就以Excel來說吧,假使要你在一堆資料中,找出儲存格中內容中有包含「網頁」的字串,而且結尾必須是「好簡單」。你能立馬知道有哪些函數可以幫助你完成嗎?我很常說,工具它只是工具,還是幫手,就單看你怎麼使用。條條道路通羅馬,在完成結果的過程中,你是要走捷徑還是繞徑,就會影響你的效率甚大。
而CSS3選擇器的組合使用,就看你對它知道多少。這麼多的方式,不可能每一樣都經常會使用到,但至少當遇到問題時要能知道方向在哪裡。好比說,你會在技術討論區看過一堆新手的發問,明明只要一個站內搜尋就可以解決,偏偏還要發問讓人損!這真的不能怪罪他們,因為他們連搜尋的關鍵字要打什麼都不知道,不是嗎?所以多接觸是好事,有方向才會知道怎麼找答案。這次就來介紹幾個在CSS中好用的選擇器。
1. 通用選擇器「*」:
星號標誌意旨所有元素,相信你在網路上經常看到下面的編碼,用來將margin與padding歸零。但如果可以,真的建議別用在生產環境的代碼中,因為可能會造成瀏覽器負擔,有時甚至可能是沒必要的編寫方式。

2. 子選擇器:
既然是子選擇器,就一定會有父子關係,先來看以下下面的例子,在class=”demo”下的li都會套用到紅色字體的設定。


當我在其中一個li中再插入一個項目清單,可以看到顏色直接套用。

主要是因為當我們使用空格方式時,是會影響到「後代所有的元素」,當把空格改成「>」時,就只會影響到子元素層級,後來所插入的清單並非父子關係,所以就不會被直接套用。

3. 型態選擇器:
型態選擇器又稱標籤選擇器,主要套用在HTML標籤上,如下面的例子,直接就可將樣式套用在ul與li標籤上。

結果:

4. 屬性選擇器:
作用是針對標籤中有特定屬內容的會套用CSS設定,在HTML5中新增的data-* attribute屬性,就很適合搭配使用,總共6種方式,如果有接觸過正則表達式的人,應該就不陌生。
以剛才的範例,在li中加入了data屬性:

[ attribute ]:
將CSS套用在標籤中有「data-index」屬性的li 元素


[ attribute = value ]
將CSS套用在屬性「data-index = ‘1’」的li 元素


[ attribute ~= value ]
將CSS套用在屬性data-item 中有包含”sample”的所有元素


[ attribute ^= value ]
將CSS套用在屬性data-item 中以”d”開頭的所有元素


[ attribute $= value ]
將CSS套用在屬性data-item 中以”g”結尾的所有元素


[ attribute *= value ]
將CSS套用在屬性data-item 中有包含”o”的所有元素,你可能會覺得與[ attribute ~= value ]有點類似,使用「~」算是完全比對,也就是屬性中的值與完全等於你指定的字串,而「*」屬模糊比對,只要有包含即可。


使用屬性選擇器,就可以一次將網頁中結尾是.jpeg的圖片做CSS設定,或是特定網頁連結的效果設定等等......。
5. 同層選擇器:
又分同層相鄰(+)與同層全體(~),以下面案例來說,在加上「+li」時,依照前面屬性選擇器來看,只要有data-index=’2’的元素會被套用,也就是cat的元素。但因使用了「同層相鄰」結果就是只有bear字體會變成紅色。


相同的,當使用了同層全體時,在cat後方相同層級的li就都會套用。


應該不難觀察到,只會套用在指定元素之後的同層元素,之前的同層元素則會保持原樣。
6. 偽類&偽元素:
很多人可能會分不清楚這兩者的差別,這邊用簡單的方式來說,偽類可把它想成是狀態的設定,例如連結樣式的設定,滑鼠滑過、連結樣式、點擊後的連結樣式等等,而偽元素可以想成始選取元素的指定部分。例如大家最熟悉的「before」與「after」。由於W3C中這類的型態相當多,列舉幾個大家最常使用的。
偽類:

偽元素:
:first-line、:first-letter、:before、:after
結構中的使用大同小異,主要都是用來挑選特定的元素,以這邊的案例來說,nth-child(1),就會選定「dog」的li元素,也等於「:first-child」。

相對的,「: last -child」、「nth-last-child(1)」相同,都是指向最後一個li元素。first-child與last-child不能指定,分別指向第一個與最後一個元素。而nth-child與nth-last-child必須要給予一個正整數的參數,以1為基數。下例就是指定倒數第二個元素。

搞懂這些選擇器,開發上就可以將樣是快速的套用到指定的位置上,不要將樣式表一層一層指定,不僅增加檔案大小,閱讀上也相當不便,如果你覺得這篇文章很實用,也別忘了分享給你的親友們,相信對他們一定很有幫助!
加入菜鳥救星官方Line並回覆「我想看文章」,不定期獲得更多知識吧!
不同頻道,不同知識!
Facebook Instagram Youtube