支援CSS3 以上 用法: :only-child 說明: 父元素的是唯一的子元素則套用 css定義: 父元素唯一的子元素是且是a tag則套用 a:only-child{ font-size: 20px; color: silver; } 父元素唯一的子元素是且是p tag則套用 p:only-child{ font-size: 20px; color: red; } 注意事項: 程式: <!DOCTYPE html> <html> <head> <title>css3 Selector only-child 套用樣式</title> <meta http-equiv="Content-Type" content="text/html; charset=BIG5"> <style type="text/css"> a:only-child{ font-size: 20px; color: silver; } p:only-child{ font-size: 20px; color: red; } </style> </head> <body> <a href="#1">a tag test 1</a> <div id="div1"> <a href="#1">div 1 a tag test 2</a> </div> <div id="div2"> <a href="#1">div 2 a tag test 3</a> <a href="#1">div 2 a tag test 4</a> </div> <p>p tag test 1</p> <div id="div3"> <p>div 1 p tag test 2</p> </div> <div id="div4"> <p>div 2 p tag test 3</p> <p>div 2 p tag test 4</p> </div> </body> </html> a:only-child 唯一的子元素且是a tag則套用 p:only-child 唯一的子元素且是p tag則套用 有子元素 的父元素 子元素數量 是否符合 body6否 div11是 div 1 a tag test 2 div22否 div31是 div 1 p tag test 2 div42否 圖1:
測試結束~ 如果還不了解可參考:w3schools CSS Selector Reference 感謝~
