I know this is a common problem but I can't seem to find a solution that works. I have a setup like this:
<div id="wrapper">
<div class="content-area-top"></div>
<div class="content-area">
<h1>Title</h1>
some other text
</div>
</div>
.content-area-top {
height: 12px;
width: 581px;
background-image: url(images/content-top.jpg);
}
.content-area {
margin-left: 10px;
margin-right: 10px;
background-color: #e9ecfd;
}
The problem is that there is a gap between .content-area-top and .content-area. the .content-area-top div is sized to contain a background image that gives me the rounded corners that I want.
I know that issue comes form the fact that the H1 tag has a (browser default) top margin set (.67em), but I'm unwilling to se开发者_如何学Ct its margin to 0, and I don't see why its margin applies 'outside' its containing div.
I'm using chrome on Mac, but firefox has the same issue. This is probably some well-known fix, but I couldn't find a a solution specific to my case.
See here for a related question:
Why would margin not be contained by parent element?
in which a great article on margin collapse is presented:
http://reference.sitepoint.com/css/collapsingmargins
The article does have some pointers.
The answer is that the margin on H1 collapses with its parent(.content-area) margin (0 in this case), and so the parent div takes on the H1 margin. To prevent that, the parent div (.content-area) needs to have a padding set or a border or something set to prevent the collapse (which, in my case, brings my two divs together correctly)
Margins aren't supposed to collapse if there is a border between them. So you can add a hidden border to prevent margin collapse.
The following worked for me in my tested versions of FF, Chrome & IE.
<!-- Set the border-color to your background color.
If default white background colour use #FFFFFF -->
<div style="background-color: #8DB3E2; border-color: #8DB3E2; border-style:solid; border-width:1px; ">
<p >Paragraph 1 in blue box</p>
<p >Paragraph 2 in blue box</p>
</div>
<!-- No space here thanks -->
<div style="background-color: #9BBB59; border-color: #9BBB59; border-style:solid; border-width:1px; ">
<p >Paragraph 1 in green box</p>
<p >Paragraph 2 in green box</p>
</div>
Try giving a valid doctype. It worked for me :)
Refer this : A list apart has said it beautifully!
Yogesh
Try this approach:
#content-area-top {
width:581px;
height:12px;
float:left;
background-image:url("images/content-top.jpg");
}
#content-area {
width:561px; /* substract margin left & right values from it's width */
float:left;
display:inline; /* prevent ie6-double-margin bug */
margin:0 10px;
background-color:#e9ecfd;
}
#wrapper {
width:581px;
float:left;
}
精彩评论