Css 将内容居中并在内部浮动

Css 将内容居中并在内部浮动,css,css-float,Css,Css Float,我对float感到困惑:我有一个div菜单,里面有两个项目。我将其居中,边距为0自动。如果我把蓝色和红色放在浮点数里,浮点数就不再居中了,不再有内容了。我不明白为什么 以下是一个例子: CSS: HTML: 一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一

我对float感到困惑:我有一个div菜单,里面有两个项目。我将其居中,边距为0自动。如果我把蓝色和红色放在浮点数里,浮点数就不再居中了,不再有内容了。我不明白为什么

以下是一个例子:

CSS:

HTML:


一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本一些文本

溢出:隐藏
添加到包装
div
如果希望菜单也居中,则必须指定其内容的宽度:


您需要指定一个宽度,因为浮动的元素不流动,并且不影响父元素(包含块)的宽度计算。

溢出:隐藏
添加到包装
div
如果希望菜单也居中,则必须指定其内容的宽度:


您需要指定一个宽度,因为浮动元素不流动,并且对计算父元素(包含块)的宽度没有贡献。

您的意思是我需要指定#菜单?的宽度,为什么有必要?
溢出:自动
也可以,同样的想法,启动一个新的格式上下文。@Nrc如果您不指定其宽度-默认情况下它将填充整个可用宽度(这是
display:block
的行为方式)-如果您想避免指定宽度-不要在菜单项上使用
float
,而是将其
display
更改为
inline block
(这在IE上不存在。你的意思是我需要指定#菜单的宽度吗?为什么有必要?
overflow:auto
也可以,同样的想法,启动一个新的格式化上下文。@Nrc如果你不指定它的宽度-默认情况下它将填充整个可用宽度(这就是
显示:block
的行为方式)-如果要避免指定宽度-不要在菜单项上使用
浮动
,而是将其
显示
更改为
内联块
(IE上不存在)
#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;
}
<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>