css - 给标题 margin-top 除非它们与容器 div 齐平?

标签 css css-selectors pseudo-class

我有一个在线文档,它有两列正文(每个段落都在 p 标签中),顶级 <h1>/<h2>标题和多个内联 <h3>的。

我用来设置列样式的 CSS 与我的问题无关,但基本的 HTML 如下:

<h1>Page</h1>
<h2>Article Title</h2>

<div.container><!--Begin container-->

  <div.col1>
    <h3>article heading level 2</h3>
    <p>Paragraph...</p>
    <h3>article heading level 2</h3>
  </div>

  <div.col2>
    <p>Paragraph...</p>
    <h3>article heading level 2</h3>
    <p>Paragraph...</p>
  </div>

...and so on

</div><!--End container-->    

我想设计我的 <h3>标签,以便顶部的标签(即每列的第一个 <h3>)与容器顶部齐平,但所有其他 <h3>标签有上边距。

最终目标是找到一种优雅的 CSS 处理方式,使我的 <h3> 成为可能。的垂直空间(顶部边距)比我的段落更大我不必通过并为每个 <h3> 添加自定义选择器.

我希望有一些方法可以使用伪类来达到这种效果。

最佳答案

你可以使用 :not(:first-child)实现这一目标:

div.container > div > h3:not(:first-child) {
   margin-top:30px;
}

这会将样式应用于所有 <h3>不是您希望的第一个 child 的元素。

jsFiddle here.

请注意:not() IE8 及之前版本不支持。

如果您碰巧正在使用 jQuery 库并且希望此选择器(除了对各种其他伪选择器的支持)在 IE8 和更早版本中工作,您可以查看 Selectivzr .

关于css - 给标题 margin-top 除非它们与容器 div 齐平?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22263992/

相关文章:

javascript - ul 和 div 中第一个 li 元素的具体行为

css - SCSS中嵌套元素+元素选择器

javascript - Jquery 的 eq(0), "..first-child", first() 如果它是一个 iframe 则不捕获第一个 child

css - 为什么这个 CSS :not() declaration filter down? 没有

javascript - <option> 元素中可以有多行吗?

jquery - 两个日期选择器,一个只显示月份

css - 显示固定 'modal' div 时的页面切换

css - 修复了 Google Chrome 中定位的 header "jumps"

html - :not() is not ignoring class in list-items with links

html - 是:root really useless?