2013-04-27 59 views
1

我對浮動感到困惑:我有一個div菜單,裏面有2項。我用margin 0自動居中。如果我把浮動的藍色和紅色不再居中,並且內容不夠用。我不懂爲什麼?居中內容和浮動內

這裏是例子:http://jsfiddle.net/A4FHd/

CSS:

#content{ 
    margin:0 auto; 
    width:400px; 
    background:yellow; 
} 

#text{ 
    margin:0 auto; 
    text-align:justify; 
} 

#menu{ 
    margin:0 auto; 
    z-index:0; 
    background:grey; 
} 

#blue{ 
    float:left; 
    width:50px; height:50px; 
    z-index:0; 
    background:blue; 
} 
#red{ 
    float:left; 
    width:50px; height:50px; 
    z-index:0; 
    background:red; 
} 

HTML:

<div id="content"> 

    <div id="text"> 
    some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text some text 
    </div> 

    <div id="menu"> 
     <div id="red"> </div> 
     <div id="blue"> </div> 
    </div> 

</div> 

回答

1

添加overflow: hidden到包裝div ,如果你想在菜單爲中心,以及 - 您必須指定其內容的寬度: http://jsfiddle.net/A4FHd/5/

您需要指定一個寬度,因爲浮動元素超出流動範圍,並且無助於計算父元素(包含塊)的寬度。

+0

你的意思是我需要指定#menu的寬度嗎,爲什麼有必要? – Nrc 2013-04-27 17:06:39

+0

'overflow:auto'也有效,同樣的想法,開始一個新的格式化上下文。 – 2013-04-27 17:07:24

+1

@Nrc如果你沒有指定它的寬度 - 它將默認填充整個可用寬度(這是'display:block'的行爲方式) - 如果你想避免指定寬度 - 不要使用'float'on你的菜單項,但改變他們的'display'到'inline-block'(IE <8不存在) – 2013-04-27 17:09:31