2010-06-04 89 views
15

我知道這是一個常見的問題,但我似乎無法找到一個有效的解決方案。我有這樣的設置:css之間的垂直差距

<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; 
} 

問題是.content-area-top和.content-area之間存在差距。 .content-area-top div的大小設置爲包含一個背景圖像,該圖像爲我提供了我想要的圓角。

我知道這個問題來自H1標籤有一個(瀏覽器默認)上邊距設置(.67em)的事實,但我不願意將其邊距設置爲0,我不明白爲什麼它保證金適用於包含div的「外部」。

我在Mac上使用chrome,但firefox有同樣的問題。這可能是一些衆所周知的修復方法,但我無法找到針對我的案例的解決方案。

+3

使用CSS復位文件,你會得到更多的瀏覽器一致的行爲。 http://developer.yahoo.com/yui/reset/ – 2010-06-04 15:09:46

+0

@durilai +1爲YUI重置! – lewiguez 2010-06-04 15:12:02

+0

我試過了,它摺疊了兩個div之間的空間,但是當我在h1上放置一個帶有餘量的樣式時,間隙就會重新出現。 真正的問題似乎是,h1上的任何邊距都超出了圍繞它的div,在我看來,邊距應該完全包含在包含div中。 – meecect 2010-06-04 15:26:43

回答

15

在這裏看到一個相關的問題:

Why would margin not be contained by parent element?

在保證金崩潰一個偉大的文章,提出:

http://reference.sitepoint.com/css/collapsingmargins

文章確實有一些指點。

答案是H1上的邊距與其父(.content-area)邊距(在這種情況下爲0)崩潰,因此父div取H1邊距。爲了防止這種情況,父div(.content-area)需要填充集或邊框或設置爲防止崩潰(在我的情況下,它將我的兩個div正確地集合在一起)

+4

+1,非常好。要重新迭代這個答案,只需在#content-area上設置一個填充頂部 – 2010-07-08 17:35:00

+0

謝謝你,這讓我難倒了 – 2013-02-13 02:54:27

0

嘗試此方法:

#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; 
} 
1

邊緣不應該崩潰,如果它們之間存在邊界。所以你可以添加一個隱藏的邊框來防止邊距崩潰。

以下在我測試版本的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> 
0

嘗試給出一個有效的文檔類型。它爲我工作:)

請參閱:A list apart已經說得很漂亮!

約傑什