您的位置:首页技术文章
文章详情页

css - 如何给html节点内的第一个子节点定义样式

【字号: 日期:2023-08-09 17:26:00浏览:50作者:猪猪

问题描述

文档结构如下

- <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

标签: HTML
相关文章: