Question

I'm having difficulties with spaces between div blocks:

<div id="maincontentwrapper" >
  <img src="images/content-top.png" alt="main content border image" border="1" />
  <div id="maincontent" >
    <div id="pagecontent">
       <h1>Mission Statement</h1>
    </div>
  </div>
  <img src="images/content-bottom.png" alt="main content border image" />
</div> 

This is creating a page with a full bordered image. All is well, however as soon as I enter a block level element inside of pagecontent, e.g. the header as shown, then a gap appears between the content-top.png image and the maincontent div.

If I change the first character to be inline, e.g. a non-breaking space or simply a letter, then the gap does not appear.

This is the (relevant) css:

img {
 margin: 0;
 padding: 0;
}
#maincontentwrapper { 
}
#maincontent {
 background-image: url('../../images/content-main.png');
 background-repeat: repeat-y;
 min-height: 300px;
 width: 757px;
}
#pagecontent {
 width: 625px;
 margin-left: auto;
 margin-right: auto;
}

Thanks for any help

Was it helpful?

Solution

It's probably a margin applied by the browser by default. Try your code with

h1 { margin: 0; }

added to the CSS. Does that help?

(The h1 element is not the only block-level element to "suffer" from this, p has default margins in most browsers too.)

If you're pretty sure your client's browser will support CSS3, you have a backup mechanism, or you just don't care, you could do

.maincontent :first-child, .maincontent :first-child :first-child {
    margin: 0;
}

which will set the first child's margin to 0, regardless of the type of the element.

Something else you could do is apply a "reset stylesheet" that undoes the browsers' defaults by masking them with zeroes. However, I would not advise you to do so, since the browsers' defaults actually make sense most of the time, and resetting them all could lead to disturbing effects.

OTHER TIPS

Have you tried another element than a H1? I believe the problem comes from the H1 element having margins by default and maybe that's what "pushing" the div down and leaving a gap. By the way, are you using Firefox's plugin Firebug to test CSS? It's really powerful and lets you modify on-the-fly.

I would say this is a problem due to browser default css settings, like those applied to h1 p, etc.

One way to get rid of this is to use some "reset" css like the one in 960grid : here

From my experience, it works fine :)

Maybe because margins are collapsing. Try to add

padding: 0 1px 0 1px;

to img or div or both.

The <img /> tag is rendered inline by default. Try display: block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top