中心浮动容器中的div

时间:2014-09-26 19:52:48

标签: html css

我目前正在制作一个不使用框架的网站,但是我遇到了一个问题。即使容器本身在体内居中,我的div也不会集中在容器中。

HTML

<body>
<div id="content">
 <div class="box">

 </div>
 <div class="box">

 </div>
 <div class="box">

 </div>
 <div class="box">

 </div>
</div>

的CSS

#content{
    width: 90%;
    height: 100%;
    margin: 0 auto;
}

.box{
    width: 400px;
    height: 150px;
    float: left;
    border: 1px solid #c8c8c8;
    border-radius: 3px;
    margin: 13px;
}

当我的窗口达到全宽时,div完全居中,但是一旦我调整它,它们就会重新组织而不会居中。

调整大小之前: http://cl.ly/image/241R2I24280w/Screen%20Shot%202014-09-26%20at%2021.49.23.png 调整窗口大小后:http://cl.ly/image/2y2g2W0n230g/Screen%20Shot%202014-09-26%20at%2021.50.21.png

我尝试了不同的方法来解决它,比如做margin: 0 -10%;margin: 0 25%; 谈到定位我很困惑。 感谢。

5 个答案:

答案 0 :(得分:2)

只需像这样更改你的CSS,这样你就可以通过多种方式调整你的盒子,他们会按预期对响应式布局做出反应:

#content {
    width: 90%;
    height: 100%;
    margin: 0 auto;
    text-align:center;
    display:block;
}
.box {
    width: 45%;
    height: 150px;
    display:inline-block;
    border: 1px solid #c8c8c8;
    border-radius: 3px;
    margin: 13px 2%;
}

See fiddle here

说明:

我已移除您的花车,使用了块元素并以百分比替换了您的固定尺寸。然后,我在容器框text-align:center中使用了#content属性,因此一切都在该容器的中心很好地对齐。现在,如果您调整大小,列将占据屏幕宽度的45%,但您显然可以通过媒体查询更改行为,并使用类似.box{display:box}的小屏幕

答案 1 :(得分:1)

您的问题有多种解决方案。根据您在这些框中的内容,这可能是最简单的:text-align:centerdisplay:inline-block组合;见这里。Fiddle

答案 2 :(得分:0)

2个解决方案: 您可以使用百分比作为boxes

的宽度
#content{
    width: 90%;
    height: 100%;
    margin: 0 10%;
}

.box{
    width: 30%;
    height: 150px;
    float: left;
    border: 1px solid #c8c8c8;
    border-radius: 3px;
    margin: 13px;
}

Boxes会根据内容调整大小,但框中的内容可能看起来很小。

或者 您可以使用像素值作为content的宽度。

#content{
    width: 1200px;
    height: 100%;
    margin: 0 10%;
}

.box{
    width: 400px;
    height: 150px;
    float: left;
    border: 1px solid #c8c8c8;
    border-radius: 3px;
    margin: 13px;
}

调整大小时框的宽度不会改变,也不会改变其中的内容,但在小屏幕上可能会很痛苦。

答案 3 :(得分:0)

为您的包添加自动保证金

.box{
    width: 400px;
    height: 150px;
    border: 1px solid #c8c8c8;
    border-radius: 3px;
    margin-top: 13px;
    margin-left:auto;
    margin-right:auto;
    }

答案 4 :(得分:0)

我在我的机器上制作了你的文件并且div没有居中,所以我假设你的屏幕或分辨率设置不同,或者你的内容容器在一个或多个其他div中?

无论如何,请尝试添加&lt; clear; left;&#39;在你的盒子类代码中它应该解决你的问题(把它放在&#39; float:left&#39;行上面。祝你好运!