Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do the <p> and <h1> elements cause gaps in my layout?

Tags:

html

css

If I have the following html:

<body>
    <div id="mainTop">
    </div>
    <div id="main">
        <h2>
            <%= Html.Encode(ViewData["Message"]) %></h2>
        <p>
            To learn more about ASP.NET MVC visit 
                http://asp.net/mvc</a>.
        </p>
    </div>
    <div id="mainBottom">
    </div>
</body>

With the following CSS:

#mainTop
{
    background: url('/Content/Images/bg_top.png') no-repeat;
    width: 963px;   
    height: 65px;
    margin: 0 auto;
    text-align: left;
    color: #5d676d;
}

#main
{
    background: url('/Content/Images/bg_middle.png') repeat-y;
    width: 963px;   
    min-height: 50px;
    margin: 0 auto;
}

#mainBottom
{
    background: url('/Content/Images/bg_bottom2.png') no-repeat;
    width: 963px;   
    height: 128px;
    margin: 0 auto;
}

It looks like this:

alt text

Why do certain tags like <p> and the heading tags cause gaps in my layout? Ideally, I would like to not have those huge spaces in between my content.

like image 333
KingNestor Avatar asked Jun 15 '09 15:06

KingNestor


3 Answers

By default <p> and <h2> (among others) have margins and paddings associated with them. Trying adding the following to your CSS:

p, h2 {
  margin: 0px;
  padding: 0px;
}

Having padding won't affect the border and background of the elements, but depending on what you want, you might want to try removing them as well as I do here.

Edit: as Guffa pointed out in an answer below, the reason that the margins of the paragraph and heading are reaching outside their container DIVs is due to collapsing margins.

like image 52
JoeCool Avatar answered Oct 18 '22 16:10

JoeCool


To avoid situations like this, use something like YUI Reset. It sets the default CSS to something predictable across browsers.

like image 22
scvalex Avatar answered Oct 18 '22 18:10

scvalex


That is because of collapsing margins. Margins aren't something that surround a single element, like padding. Instead the margin determines the distance between elements. If the parent element doesn't have margin or padding (like the div elements in your code), the margin of the child elements (h2 and p) determine the distance between the parent elements rather than the child elements.

For now you should generally avoid collapsing margins when the parent elements have a background set, as IE (at least up to version 7) doesn't handle collapsing margins correctly.

If you just set some padding on your div elements (it looks like you should have that anyway), the margins won't collapse outside them.

like image 27
Guffa Avatar answered Oct 18 '22 17:10

Guffa