2013-06-30 41 views
2

我有一個小問題,我不知道它爲什麼會發生。我有2個div包裝器,一個所謂的「mainWrapper」,它有一個背景圖像和一個名爲「loginWrapper」的div的子元素。 我希望登錄包裝從上面定位15%,但如果我只是添加餘量,它似乎也會更改父div(mainWrapper)的餘量。div div div margin margin of parent div

有人可以向我解釋爲什麼會發生這種情況,我該如何解決?

代碼:

HTML:

<div id="mainWrapper"> 
    <div id="loginWrapper"> 
     <h:graphicImage id="logo" alt="spotted deluxe" url="resources/images/logo.png" /> 
    </div> 
</div> 

CSS:

body,html{ 
    height:100%; 
} 

body { 
    margin:0; 
    background-color: green; 
    background: url(../images/backround_red.png) no-repeat center center fixed; 
    background-size: cover; 
} 

div#mainWrapper { 
    text-align: center; 
    margin: auto; 
    width:70em; 
    height:100%; 
    background: url(../images/header.jpg) no-repeat center center fixed; 
    background-size: cover; 
    padding-left:4em; 
} 

div#loginWrapper { 
    /*margin-top: 15%;*/ 
} 

img#logo { 
    display: inline; 
} 

回答

2

是的,這將增加保證金父。請試試位置。\

div#mainWrapper { 
    position: relative; 
} 

div#loginWrapper { 
    position: relative; 
    top: 15%; 
} 
+1

thanx它確實這樣工作:) –

2

這是margin collapsing的特殊情況。一些選項,以防止它是:

  1. 添加1px的填充,頂部或邊框頂父DIV
  2. 讓父DIV建立新的block formatting context(例如,通過向它添加溢出:隱藏或改變其顯示以顯示:表格
  3. 添加到父div:在僞元素之前使用display:table,如在流行的Micro Clearfix hack中。