Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: bottom margin of H2 directly after H1

Tags:

css

margin

header

I'm looking for a way to give H1 more margin-bottom (or H2 more margin-top) in case h1 and h2 directly follow each other. So in case #1 the normal margins should apply but in case #2 I like to change the margins a bit (to give more "air" between H1 and H2). Tried using h1 h2 {margin...} and h1>h2 {margin...} but so far no success.

Case #1

<h1>heading 1</h1>
<p>text</p>
<h2>heading 2</h2>
<p>text</p>

Case #2

<h1>heading 1</h1>
<h2>heading 2</h2>
<p>text</p>
like image 400
luvTweb Avatar asked Jan 31 '26 16:01

luvTweb


2 Answers

h1 + h2 {
  margin: whatever;
}

The + selector is the adjacent selector. It will only affect elements that are adjacent to the preceding element.

like image 128
Jamey Avatar answered Feb 02 '26 16:02

Jamey


Try something like:

h1+h2{
   margin-top:10px;
}

It uses the adjacent selector. See http://www.quirksmode.org/css/selectors/ for browser compatibility information.​

like image 41
Joshua Dwire Avatar answered Feb 02 '26 17:02

Joshua Dwire