3

Below is my HTML structure

<div class="ContentHeader">
   <hgroup>
      <h1>Title</h1>
      <h2>Subtitle</h2>
   </hgroup>
</div>

I'm looking for a solution to the issue that doesn't use javascript, I know I can do that but I'd prefer if there was a CSS only solution.

I want to only style the h1, if the h2 also exists. So, if there is no h2, then there is no styling applied to the h1.

I tried this but it only styled the h2

.ContentHeader hgroup h1 + h2 {
  padding-bottom: 10px;
}

Any help would be greatly appreciated.

mcclosa
  • 943
  • 7
  • 29
  • 59

3 Answers3

3

You could use this:

.ContentHeader hgroup h1:nth-last-child(2) { /* your code here */}
Luke
  • 106
  • 3
1

You can make both of the headings to same element.

<div class="ContentHeader">
   <hgroup>
      <h1>Title</h1>
      <h1>Subtitle</h1>
   </hgroup>
</div>

Then you can use only child property in CSS

.ContentHeader hgroup h1:only-child {padding-bottom: 10px;}

See here:

.ContentHeader hgroup h1:only-child  {
  padding-bottom: 10px;
  color:red;
}
<div class="ContentHeader">
   <hgroup>
      <h1>Title</h1>
      <h2>Subtitle</h2>
   </hgroup>
</div>

<div class="ContentHeader">
   <hgroup>
      <h1>Title</h1>
   </hgroup>
</div>
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
  • For SEO purposes we only use one H1 per page, multiple h1's makes it difficult for Google to contextualise the page. – mcclosa Jul 04 '18 at 08:32
  • I agree, then you can wrap headings in two hgroups or div's with same class and then use only-child pseudo class on that class – Tasawar Hussain Jul 04 '18 at 13:48
0

That's not possible in css (nor sass). Css does not look back. Styling an element that's after another element is possible, not the other way around.

You can possibly achieve the same result by not giving a padding/margin bottom to the h1, but a padding/margin top to the h2. If that will not help you, javascript is probably your only option.

giorgio
  • 10,111
  • 2
  • 28
  • 41