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
相关文章:
1. docker start -a dockername 老是卡住,什么情况?2. dockerfile - [docker build image失败- npm install]3. 老师,CSS3里面,选择一个DIV,这个DIV是以什么为原点进行旋转的啊?4. angular.js - 使用angular-xeditable报错5. 数据库设计 - Binary Allow Null Default mysql数据库字段属性问题 ?6. angular.js - 我用ng-repeat出来的数据为什么在IE11中只显示{{week}}?7. java - jstl中c标签无法解析报错如何解决8. mysql每隔10来秒就有一次7、8MB的写入9. php laravel框架模型作用域10. PHP中的$this代表当前的类还是方法?