0

Given:

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

I know that I access the second h2 and can apply some spacing below that element by doing:

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

However, some of my sections only contain a single header line like:

<h2>Catchy Tagline!</h2>

Can I selectively access and apply something like padding-bottom: 20px; to the h2:first-child when there is only one h2 element?

Otherwise, I would be adding a 20px space between any/all h2 tags and I want them to stay set at 0 margin/padding if they are stacked as my first example shows.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
armadadrive
  • 963
  • 2
  • 11
  • 42

1 Answers1

2

You can do that with :only-of-type:

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

If you need to apply the style only when the lone h2 is the first child, you should not replace the :first-child with :only-of-type but add it so you have both pseudo-classes:

h2:first-child:only-of-type {
  padding-bottom: 20px;
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • Is `only-of-type` supported by all modern browsers? I have never seen that pseudo-class before. – armadadrive Mar 15 '16 at 15:51
  • @armadadrive: Yes, if you've seen :first-of-type, :only-of-type was introduced at the same time and is not new, and support is identical. – BoltClock Mar 15 '16 at 15:52
  • I just had a brief look at the MDN entry - would `first-child` be redundant in this case? – armadadrive Mar 15 '16 at 15:55
  • I haven't tried it, but it seems to me that only-of-type would find nothing if a child had siblings? – armadadrive Mar 15 '16 at 15:56
  • @armadadrive: It wouldn't always be redundant - see [this answer](http://stackoverflow.com/questions/24657555/what-is-the-difference-between-first-child-and-first-of-type/24657721#24657721) for an illustration (it says :first-of-type, but you can treat :only-of-type as equivalent to :first-of-type:last-of-type). – BoltClock Mar 15 '16 at 15:57
  • 1
    @armadadrive: Or, more succinctly: consider a div that contains a p and a span. The p and span are each the only siblings of their type, but they are siblings of one another - the p is the first child, and the span, the last. – BoltClock Mar 15 '16 at 15:58
  • Oh! I've been thinking of last-child incorrectly and it just happened to work in most cases. If I do: `p:last-child` but it's followed by a
      , say, that won't work because it's not the last child?
    – armadadrive Mar 15 '16 at 16:00