CSS 選擇“子孫”與“弟弟妹妹”

紅寶鐵軌客
Join to follow...
Follow/Unfollow Writer: 紅寶鐵軌客
By following, you’ll receive notifications when this author publishes new articles.
Don't wait! Sign up to follow this writer.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.
寫程式中、折磨中、享受中 ......
728   0  
·
2017/11/04
·
3 mins read


又到了英文課時間了,今天要講的是 CSS 的 selectors 選擇器⋯⋯

說笑了,其實,只是我自己想做個筆記,一切又是因為那個萬惡的 Turbolinks,我又碰到了奇怪的怪異 javascript 行為,一路查 Bug 到無解,因為 Bug 又不見了,只有寫寫紀錄,消消氣,剛好有人問這,就順手寫下了。

在 CSS 裡,要選擇相關連的組件,有兩組很好用的選擇器,他們都有一對選擇關係:一個是緊鄰關係,另一個不用是緊鄰關係:

子孫關係:

.a > .b vs. .a .b 

.a > .b 是選擇 children,也就是小孩,所謂的小孩,就是直接的關係,不是孫子,更不是曾曾曾孫,這是緊鄰關係。

.a .b 是選擇 decendant,也就是子孫,也就是後代、後裔啦,所以,小孩也算,孫子也算,曾曾曾孫也算,這就是不緊鄰關係。

例如:

<div class="a">
  <div class="b">
  <div class="c">
  </div>
  <div class="c1">
  </div>
  <div class="c2">
  </div>
  </div>
</div>
  • .a > .b 會選到02 .b
  • .a .c 會選到03 .c
  • .a > .c 會選不到,因爲 .c 不是 .a 小孩,是孫子,不是緊鄰關係。

這個選擇器討厭的地方是,“ > ” 是選小孩,這跟我們數學上常用的習慣不同,我們直覺上會覺得 “ > ” 應該是子孫,這就是討厭的地方。

弟妹關係:

同樣關於兄弟姊妹 (sibling)關係,也有一對選擇關係:也是一個緊鄰關係,另一個不用是緊鄰關係,兄弟姊妹 (sibling)關係又有限制,只能找弟弟妹妹,不能找哥哥姊姊

.a + .b vs .a ~ .b

.a + .b 是選擇 next sibling,就是「結著出生的弟弟妹妹」,是直接的關係,要結著生的才算,不只是弟弟妹妹就行,這是緊鄰關係。

.a ~ .b 是選擇 general next sibling,也就是「弟弟妹妹都可以」,可以是二弟五妹,這就不是緊鄰關係。

  • .c + .c1 會選到05 .c1
  • .c ~ .c2 會選到07 .c2
  • .c + .c2 會選不到,因爲 .c2 不是 .c 「隔壁」,不是緊鄰關係。
多重選擇:

還有一個很常搞亂的就是兩個以上的選擇器中間沒有「空白」,這就不是選子孫或是選兄弟關係了,這是要選一個「同時」都有的多從選擇,舉例來說:

<div class="red"> </div>
<div class="yellow"> </div>
<div class="red yellow"> </div>

.red.yellow 就會選到那個同時有 .red 也有 .yellow 的 div,順序時沒有關係的。 

搞昏了不要怪我,CSS 還有更多很昏的選擇器啊!


WriterShelf™ is a unique multiple pen name blogging and forum platform. Protect relationships and your privacy. Take your writing in new directions. ** Join WriterShelf**
WriterShelf™ is an open writing platform. The views, information and opinions in this article are those of the author.


Article info

分類於:
標籤:
日期:
創作於:2017/11/04,最後更新於:2018/11/02。
合計:658字


Share this article:
About the Author

很久以前就是個「寫程式的」,其實,什麼程式都不熟⋯⋯
就,這會一點點,那會一點點⋯⋯




Join the discussion now!
Don't wait! Sign up to join the discussion.
WriterShelf is a privacy-oriented writing platform. Unleash the power of your voice. It's free!
Sign up. Join WriterShelf now! Already a member. Login to WriterShelf.