Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paragraph tag adds empty space between sections

Tags:

html

css

When I begin or end a section of my HTML document with a <p> tag, it adds an "unclaimed" space between preceding/trailing sections.

Example:

<!DOCTYPE html>
<html>
<style>
header {background-color: gray}
div.content {background-color: lightblue}
footer {background-color:gray}
</style>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="initial-scale=1.0,width=device-width">
  <title>This is the title.</title>
</head>
<body>
  <header>
  This is the header.
  </header>
  <div class="content">
    <p>This is paragraph #1</p>
    <p>This is paragraph #2</p>
  </div>
  <footer>
    This is the footer
  </footer>
</body>
</html>

Result:

Space outside tags

Notice the space inserted above and below the <body> due to the <p> tags. There are a few things I can do to fix the formatting: I can remove the <p> tags and instead use <br /> to style the text into paragraphs.

However, I ask this question because I would like to understand

  1. Why doesn't the <body> section include the <p> spacing? What section does the <p> spacing "belong" to, if any?
  2. Following the intent of the <p> tags, or HTML tagging in general, is there a "right" way to work around this behavior to both mark my paragraphs and get the format that I want (no white spaces between sections).

To be clear, I was expecting to see something like this:

enter image description here

... or this:

enter image description here

Thanks!

like image 304
Terrabits Avatar asked Aug 12 '26 19:08

Terrabits


1 Answers

The default margin spacing with many major browsers is 1em before and after the p tag. Below is a screen capture within Chrome Developer Tools showing the default user agent stylesheet that is applied to all p tags, until it is overwritten.

enter image description here

Check out this fiddle that has no changes to the paragraph tag at all

EXAMPLE 1

Then compare it to this one below. Notice that I have added some CSS of margin:0; to remove the default margins that the user agent stylesheet applies.

EXAMPLE 2

p {
     margin:0;
}
like image 194
Fizzix Avatar answered Aug 14 '26 11:08

Fizzix