2015-12-27 18 views
2

爲什麼內容div上的邊距還會推入intro div?我覺得在嵌套div時我犯了一個非常愚蠢的錯誤,但我真的不知道。嵌套div中的垂直邊距未按預期方式工作

body { 
 
    margin: 0px; 
 
} 
 
div.content { 
 
    text-align: center; 
 
    margin-top: 35px; 
 
    border-style: solid; 
 
} 
 
h1 { 
 
    display: inline-block; 
 
    margin: auto; 
 
    font-family: Lane; 
 
    color: white; 
 
    font-size: 80px; 
 
} 
 
div#intro { 
 
    background: blue; 
 
    height: 100%; 
 
    width: 100%; 
 
}
<div id=intro> 
 
    <div class=content> 
 
    <h1>Text</h1> 
 
    </div> 
 
</div>

回答

4

這是存在的,因爲垂直margins are collapsing

Box Model 8.3.1 Collapsing margins

在CSS中,兩個或多個箱(這可能會或可能不會是兄弟姐妹)的相鄰邊緣可以結合起來,形成一個單一的餘量。據說這種方式結合在一起的利潤率會崩潰,並且由此產生的綜合利潤率被稱爲摺疊利潤率。

當兩個或更多邊距摺疊時,所得邊距寬度是摺疊邊距寬度的最大值。在負邊界情況下,負邊界的絕對值的最大值從正邊界的最大值中扣除。如果沒有正邊距,則相鄰邊距的絕對值的最大值從零中扣除。

查看relevant spec以查看適用於所有可能的解決方法的規則。

例如,一個規則是:建立新的塊格式化上下文元素(如浮標,並與overflowvisible其他元素)的

頁邊距不與他們在流動兒童崩潰。

因此,你的情況,你可以簡單地在#intro元素的overflow屬性更改爲比visible默認值以外的東西。值,如auto/hidden將工作:

body { 
 
    margin: 0px; 
 
} 
 
div#intro { 
 
    background: blue; 
 
    height: 100%; 
 
    width: 100%; 
 
    overflow: auto; 
 
} 
 
div.content { 
 
    text-align: center; 
 
    margin-top: 35px; 
 
    border-style: solid; 
 
} 
 
h1 { 
 
    display: inline-block; 
 
    margin: auto; 
 
    font-family: Lane; 
 
    color: white; 
 
    font-size: 80px; 
 
}
<div id=intro> 
 
    <div class=content> 
 
    <h1>Text</h1> 
 
    </div> 
 
</div>

+0

完美的作品!謝謝。 – Rocky

0

隨着 「文本」 兩個div的裏面,他們很可能會成爲一個單一的股利。此外,如果您不使用<body></body>標籤,那麼「身體」樣式就沒有任何意義。更完整的HTML可能會幫助我們爲您提供解決方案。

+0

我只是展示了重要的部分; body,head,title和html標籤都在那裏。 – Rocky

+0

@ BlueFeather3 WRT你的評論_「身體」風格意味着什麼,如果你不使用和 tags_,那是不正確的。 –