2016-07-15 97 views
-1

如何对齐父代中心的所有左浮动元素?

.main-container{width:100%;height:auto;padding:0px;background-color:#FF0000;} 
 
.sub-container{width:50%;height:auto;padding:10px;box-sizing:border-box;margin:0px;background-color:#00FF00;float:left;text-align:center;margin-top:10px;} 
 
.child{width:100px;height:30px;line-height:30px;text-align:center;border-radius:2px;background-color:#FFFF00;float:left;margin:2px;}
<div class="main-container"> 
 
    <div class="sub-container"> 
 
    <div class="child"> 
 
     First 
 
    </div> 
 
    <div class="child"> 
 
     Second 
 
    </div> 
 
    <div class="child"> 
 
     Third 
 
    </div> 
 
    <div class="child"> 
 
     Fourth 
 
    </div> 
 
    </div> 
 
</div>

我要对齐的.sub-container在中心的内容,而无需对.child使用属性display: inline-block;

+0

为什么'inline-block'不是选项? – Shaggy

+0

对不起,但内联块不是一种选择,因为我“想”使用'浮动'属性..! –

+0

居中的第一条规则是**不使用浮动**。 –

回答

1

在这里看到:jsfiddle

编辑:使用display:flexjustify-content:center.sub-containerdisplay:inline-block.child

或者你可以使用上.childfloat:left,它仍然有效。但我建议,当你想中心未便您不使用浮动

代码:

.child 
{ 
width: 50px; 
height: 30px; 
text-align: center; 
border-radius: 10px; 
background-color: #FFFF00; 
display:inline-block; 
} 

.sub-container 
{ 
width: 50%; 
height: auto; 
padding: 10px; 
box-sizing: border-box; 
margin: 0px auto; 
background-color: #00FF00; 
float: left; 
text-align: center; 
position:relative; 
display: flex; 
justify-content: center; 
} 

让我知道,如果这是你要找的

+0

对不起..!但.child是导航按钮,所以我不能使用那么大的宽度.....! –

+0

编辑我的答案。 –

+0

如果我使用属性'display:flex',我将使用以下媒体查询来更改调整浏览器窗口大小时.child的宽度..: \t @media仅限屏幕和(最大宽度:300px) \t { \t \t .child \t \t { \t \t \t宽度:100%; \t \t} \t} \t但是因为我正在使用属性'display:flex''在.sub容器中,所以这个媒体查询将无法正常工作...! –

0

什么添加到.main-container { margin: 0 auto; display: table; }和删除width:100%;

0

也许这可以帮到你: 添加保证金50% - 容器宽度的一半。只是一个免责声明:这在某些浏览器中不受支持。

.child 
{ 
width: 100px; 
height: 30px; 
margin-left: calc(50% - 50px); 
text-align: center; 
border-radius: 10px; 
background-color: #FFFF00; 
float: left; 
}