css - 如何給html節點內的第一個子節點定義樣式
問題描述
文檔結構如下
- <article> |- <h1> or <h2> or <p> or ... # 第一個子節點,出現內容不確定 |- <h1> or <h2> or <p> or ... # 第二個子節點,不受第一個影響 |- <h1> or <h2> or <p> or ... # 同上
如上面的代碼所示,由于 h1, h2, p 這些具有不同的 margin-top,我想將緊跟著的這些元素的 margin-top 都重置為 0,但同時不影響后面出現的這些 tag,應該用什么方法?
更新:附上使用 first-child 后的效果:http://jsfiddle.net/Ygdfc/1/
問題解答
回答1:如果使用 css3 的話,可以用:
/* 選擇第一個子元素 */article h1:first-child{ margin-top:0;}
鑒于某知名瀏覽器(我也不知道哪個瀏覽器,呵呵)對 CSS3 不夠支持,可以使用大名鼎鼎的 jquery 來解決。
$('article h1:first-child').css('margin-top',0);回答2:
CSS2 也支持第一個子節點的選擇符:
article > h1, article > h2, article p { /* CSS here */}
參考:
http://www.w3.org/TR/CSS2/selector.html#child-selectors
相關文章:
