2012-07-08 54 views
3

可能重複:
CSS properties being passed up to the parent element when the DIV is empty嵌套的盒子向下推動的margin-top

我對CSS佈局結構的新手。

我現在想要做的是我想製作兩個Div盒子,一個嵌套在另一個盒子裏面。無論如何,我的問題是我設置到內框的上邊距不符合我的要求。

PLS採取以下例如腳本的一部分:

[demo.html]

<html> 
    <header> 
     <title>Mock-up page</title> 
     <link href="stylesheets/demo.css" rel="stylesheet" type="text/css"> 

    </header> 
    <body> 
     <div id="box1"> 
      <div id="box2">div 2</div> 
     </div> 
    </body> 
</html> 

[demo.css]

#box1{ 
    width: 300px; 
    height: 300px; 
    background-color:#0000FF;  
} 

#box2{ 
    margin-top: 30px; 
    background-color:#008000; 
} 

的影響它產生它只是將外框從身體標籤(圖片中的左側)向下推30px,這不是我的原本預計(圖片中的右側)。

enter image description here

是什麼,爲什麼發生這種情況以及如何糾正造型的原因是什麼?

+0

看到這一點:http://stackoverflow.com/questions/2680478/margin-top-push-外部下跌 – vsync 2013-04-08 14:54:24

回答

1

更改margin-toppadding-top會做你想要什麼。

這是許多瀏覽器中的一個常見問題。
當一個元素的第一個子元素有一個margin-top(在它之前沒有內容)時,邊距會溢出父元素的頂部,並按照您的情況推送它。

其他解決方案存在,但所有的人都有點哈克:

  • 應用的位置:對於孩子,改變margin-topmargin-bottom和應用top: 20px;;

  • 創建具有一些內容內箱之前的元素(& NBSP;這裏可以使用)配有height: 0;overflow: hidden;;

  • 設置一個border-top: 1px solid transparent或相同顏色的元素的背景(在這種情況下,要注意的是,邊框被添加到對象的高度;

  • 等等...

0

您可以將position: relative添加到#box1和position: absolute到#box2。

this example

CSS Positions Explained

+1

對於初學者來說,這是一個很好的資源,但在這種情況下,定位是過度的。 – rcdmk 2012-07-08 16:59:42

+0

@rcdmk對,你是對的 – menislici 2012-07-08 17:09:10

0

CSS

#box1{ 
    display:block; 
    width: 300px; 
    height: 300px; 
    background-color:#0000FF; 
    border:solid transparent 1px;  
} 

#box2{ 
    margin-top: 30px; 
    background-color:#008000; 
} ​ 

HTML

<div id="box1"> 
    <div id="box2">div 2</div> 
</div>​ 

如果你保持外框空(沒有文本節點),然後它正在做這種行爲,說實話我不明白爲什麼,但我發現它here爲什麼它這樣做,它被稱爲collapsed margin,我已經添加border:solid transparent 1px;來解決問題但也可以使用外部填充DIV。這裏也是對SO的回答。

Demo.

+1

請記住,這將增加每個邊的邊框寬度(例如:'height' ='height' +'border-top-width' + (我認爲IE 6和7沒有) – rcdmk 2012-07-08 17:03:37

+1

我認爲填充外/父div將是更好的解決方案。 – 2012-07-08 17:05:08