2013-08-30 18 views
2

我有這樣的網頁。H3正在佔用比封閉div更多的空間

<html> 
<head></head> 
<body> 
    <div style="background:blue"> 
     <h3 style="background:green">Hello world.</h3> 
    </div> 
</body> 
</html> 

當我在chrome中分析輸出時,看起來h3標籤佔用的空間比div標籤更多。我希望div標籤完全包含h3標籤,並在整個區域顯示div的背景顏色。任何想法如何做到這一點?

+0

'div {display:inline-block; }''h3 {line-height:0; }' – Xareyo

+0

你所看到的叫做* margin collapse *。 – cimmanon

回答

3

出現這種情況的原因是,一些元素都默認瀏覽器的造型,這就是爲什麼你應該總是使用css reset

如果您浮動div,它將環繞元素,並將h3的邊距設置爲0.

<div style="background:blue;float:left;"> 
    <h3 style="background:green;margin:0;">Hello world.</h3> 
</div> 

fiddle

爲div取整個屏幕的大小刪除浮動。

<div style="background:blue;"> 
<h3 style="background:green;margin:0;">Hello world.</h3> 
</div> 
+1

浮動根本不需要;將邊距設置爲0就足夠了。 – LeBen

+0

@LeBen我分開了整個屏幕要求:D相應地編輯了答案。 –

+0

我想我們現在也是朋友。 – Thomas

2

h3設置一個font-sizeline-height像這樣:

h3 { 
    font-size: 16px; 
    line-height: 1em; } 
3

像這樣

DEMO

CSS

.div1{ 
    background-color:blue; 
    float:left; 
} 
h3{ 
    margin:0; 
    padding:0; 
    background:green; 

}

DEMO1

2

最簡單的辦法我看,加overflow: hidden;到封閉DIV。

2
<h3 style="background:green;margin:0;">Hello world.</h3> 

默認情況下,h3有一個相關的餘量。所以你必須在h3標籤上添加一個margin:0。 H3來0.This

DEMO

2

設置的空白將解決這個問題。

相關問題