html - 如果元素在父元素中只出现一次,则将 CSS 规则应用于该元素

标签 html css css-selectors

给定:

 <h2>Header Line 1</h2>
 <h2>Header Line 2</h2>

我知道我访问了第二个 h2 并且可以通过以下方式在该元素下方应用一些间距:

h2 + h2 {
  padding-bottom: 20px;
}

但是,我的一些部分只包含一个标题行,例如:

<h2>Catchy Tagline!</h2>

当只有一个 h2元素?

否则,我会在任何/所有 h2 标签之间添加一个 20px 的空间,如果它们像我的第一个示例所示那样堆叠,我希望它们保持设置为 0 边距/填充。

最佳答案

你可以用 :only-of-type 来做到这一点:

h2:only-of-type {
  padding-bottom: 20px;
}

如果仅当单独的 h2 是第一个 child 时才需要应用样式,则不应替换 :first-child使用 :only-of-type 但添加它以便您拥有两个伪类:

h2:first-child:only-of-type {
  padding-bottom: 20px;
}

关于html - 如果元素在父元素中只出现一次,则将 CSS 规则应用于该元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36015963/

相关文章:

jquery - 选择 sidenav 时防止 body 滚动

html - CSS 最后一个 child 不工作

html - 在表格中调整 TD 的大小

python - Selenium Python : Element not clickable because another element obscures it

html - 列表中第一个 li 的选择器

javascript - 相对位置

html - 为什么 HTML5 不支持 font 元素?

javascript - 如何将 JS 中的值插入到 HTML 中?

html - 文本覆盖另一个文本,需要显示在下方

html - CSS :after tag with background image and %