6

I want space between my <p>content</p> tags. Not before and not after <p> tags. For example, my code is:

<div>
   <h1>A headline</h1>
   <p>Some text</p>
   <p>Some text</p>
</div>
Something

I don't want space between h1 and p which is done with zero margin on h1. But I don't want space after the last <p> tag. Is this possible without :last-child or some JavaScript/jQuery?

I can't set class="last" on the last tag because it is a CMS system.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lasse Espeholt
  • 17,622
  • 5
  • 63
  • 99

6 Answers6

14
p + p {
  margin-top: 1.5em;
}

(Although this requires a browser with better support for CSS than IE6.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
4

If you're not required to support Internet Explorer 6 (IE6) you can use:

div, h1, p { margin: 0; }
p + p { margin-top: 12px; }

If you need to support IE6, this is a dirty hack but it works without JavaScript:

div, h1, p { margin: 0; }
h1 { margin-bottom: -12px; }
p { margin-top: 12px; }

The disadvantage of this method is that you can't simply use, say, 1em for the balancing margins as they have different font sizes. You can either manually adjust as required or use pixel widths.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
cletus
  • 616,129
  • 168
  • 910
  • 942
  • But the problem with the last method is, that if I have a list after the h1 then they will float into eachother. I will go with IE7+. – Lasse Espeholt Sep 23 '09 at 06:23
  • If you can go with IE7+ then you are sorted. I'm just pointing this out for completeness because many do need to support IE6 still (sadly). – cletus Sep 23 '09 at 06:30
  • Also, it's worth pointing out that I wouldn't suggest doing this for all divs. I'd associate a class to put on the div where you want to do this where you know the format of the contents to avoid the situation like you mention. The same heading followed by list issue has the same problem with using the + selector. – cletus Sep 23 '09 at 06:43
2

Set a default bottom-margin to p, then give the last tag a class with no bottom-margin.

da5id
  • 9,100
  • 9
  • 39
  • 53
0
<div>
   <h1>A headline</h1>
   <p>Some text</p>
   <div class="paragraph-space"></div>
   <p>Some text</p>
</div>

?

0
<div>
  <h1>A headline</h1>
  <p>Some text</p>
  <p style="margin-bottom: 0;">Some text</p>
</div>
James Skidmore
  • 49,340
  • 32
  • 108
  • 136
0

If you want to make it more browser compatible, you could also use:

p { margin-top: 24px; }
h1 { margin-bottom: -24px; } /* Play with this value as necessary */

Negative margins will pull elements toward them. It's messier than I like, but when you are at the mercy of CMS generated code with no way to add classes, you have to be creative.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
rhodesjason
  • 4,904
  • 9
  • 43
  • 59