Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid CSS styling between certain adjacent elements and classes

I would like to add padding-top: 20px; between h3 and body but not if h3 is preceded by another element (e.g., h2). Is this possible?

Adding padding-top to all headings gives the desired padding when a heading is preceded by body text but an undesired padding between headlines:

enter image description here

Note that this document is Rmarkdown created using knitr, so I don't have full control over all the html. A pure CSS-solution would be preferred.


UPDATE: To anyone also using knitr for Rmarkdown, the solution turned out to be a rather complex targeting:

/* First h2 following h1 */
.level1 > .level2:nth-child(3) > h2 {
    padding-top: 0px;
}
/* First h3 following h2 */
.level2 > .level3:nth-child(3) > h3 {
    padding-top: 0px;
}

Looking at the generated HTML, I learned that the first h2 after a h1 was in the third element in level1 and that that element was called level2. Similarly for the first h3. This is what is targeted above. The structure is probably different in other documents so take a look yourself.

like image 349
Jonas Lindeløv Avatar asked Feb 23 '26 08:02

Jonas Lindeløv


2 Answers

How about

body > h3:first-child {
   padding-top: 20px;
}

That will affect only immediate child of body with a header3, with nothing in between.

Thanks to @Oram, for pointing out missing :first-child

like image 192
vfle Avatar answered Feb 25 '26 22:02

vfle


You can use the > selector plus :first-child to target only a direct h3 child.

* {
  margin: 0;
  padding: 0;
}

.test {
  background-color: #cccccc;
  margin: 10px;
  padding: 10px;
}

.test > h3:first-child { color: red; }
<div class="test">
  <h3>Targeted h3</h3>
  <p>Paragraph</p>
  <h3>h3 not targeted</h3>
</div>

<div class="test">
  <p>Paragraph</p>
  <h3>h3 not targeted because of the p tag</h3>
  <h3>h3 not targeted</h3>
</div>
like image 43
Arkellys Avatar answered Feb 25 '26 20:02

Arkellys