Controlling Pargraph Spacing Without Abusing HTML
By Adrian Sutton
There seems to be a great demand for HTML documents that don’t include white-space between paragraphs – similar to going into the paragraph formatting in Word and setting space before and space after to zero. This is very simple to achieve in HTML, but people just keep coming up with strange ways to attempt to achieve it.
The most common way people try to get around the problem is by putting their entire document in one P tag and using BRs. You can pick these people because they set their HTML editors to insert a BR on enter instead of inserting a new paragraph. The end result looks right in all browsers but destroys the semantic structure of the document. I imagine it would be much harder to navigate through the document using a screen reader too, since skipping paragraphs seems like a nice way to skim. The problem people most often run into with this approach is that their editor still treats the whole big block as a paragraph, so when they apply a heading style the entire document becomes a H1 tag with a bunch of BRs.
The other way that people try is to use DIV instead of P, this probably works better with screen readers, but has the same problem with the HTML not meaning what the user expects it to mean. In this case, it manifests as editors that wind up inserting a H1 inside the DIV instead of converting the DIV to a H1. Even worse, the editor may insert P tags on enter instead of creating a new DIV. The worst of all is when the editor inserts BRs on enter because there’s no paragraph tags to split. It all winds up getting very messy.
Fortunately, there’s a very simple solution to the entire problem that will let you just use P tags instead of all these nasty work arounds. In your stylesheet, just add:
p { margin-top: 0; margin-bottom: 0; }
No more spacing above and below the paragraphs. You have in fact done the exact equivalent of going into paragraph formatting and setting space before and after to 0. The semantic structure of the HTML is preserved, editors will know what to do with the HTML without needing to be configured and fought with, your HTML markup will be cleaner and easier to read and your content will be more accessible.
If you can’t control the stylesheet for the document, you can put the CSS inline:
<p style="margin-top: 0; margin-bottom: 0;">Paragraph content.</p>
It is important to set both margin-top and margin-bottom to 0, while every browser I’ve seen defaults to putting space between paragraphs, some browsers apply it to the top, some to the bottom and some apply it to both. Setting top and bottom to 0 guarantees it will look like you want.
Oh and don’t worry, most editors will let you press shift-enter to insert a BR when you really do have a paragraph that needs a hard line break.