1

I have a header div that I want to be flush against the top of the window. When I enclose a paragraph in the div, space opens up between the top of the window and the div. The only way to close the space is to style the paragraph:

div#header p {
  margin: 0;
}

Why does the browser, by default, create a margin for the paragraph outside the div that contains the paragraph?

Mark Myers
  • 13
  • 2

3 Answers3

1

This is likely due to collapsing margins. MDN has a good article on the topic. Basically, top and bottom margins collapse together to form a single margin between elements. This allows for specifying p {margin-top:10px;margin-bottom:10px;} and having only 10px of space between paragraphs (instead of 20px).

See this example that shows collapsed margins versus non-collapsed margins.

You can find more information in the CSS2 Box Model specification.

0b10011
  • 18,397
  • 4
  • 65
  • 86
0

If it is too much of an issue.

Add that to your CSS

*
{
    margin: 0;
    padding: 0;
}

Every browser has it's own default CSS for html tags. For example, In chrome the margin before and after the p tag is 1em which is equal to the font-size you set. While in Firefox, the margin is 0 expect from the bottom of the element, where it is 1em again.

There are 'reset' stylesheets, that removes all special styling (like padding and margin) from (almost all) elements, so you can start 'fresh'. Reset.css is a popular choice.

imbondbaby
  • 6,351
  • 3
  • 21
  • 54
-1

it just does, dont worry too much about it. put some code in to remove the margin if you want (like) you did.

here is some good reset code if you want:

/*Remove all the default margin and padding*/
{
    margin: 0;
    padding: 0;
}
html, body /*so it'll work when you specify 100% height on element*/
{
    height: 100%;
}
Math chiller
  • 4,123
  • 6
  • 28
  • 44