6

我有一个我想使用的布局的想法,但我无法让它正常工作。我希望这里有人可以提供帮助,因为我花了几个小时搜索。

布局是这样的。

一个包装 div 容纳 6 个子 div。无论包装器 div 的大小如何,这些子 div 必须始终居中

<html>
<head>
<title>Testing</title>
<style>
br.clear { clear:both; display:block; height:1px; margin:-1px 0 0 0; }
#wrapper { max-width: 960px; min-width: 320px; background: #444; margin: 0 auto; }
.box { width: 280px; padding: 10px; margin:10px; height: 260px; border: 0px; float: left; background: #fff; }
</style>
</head>
<body>

<div id="wrapper">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <br class="clear" />
</div>

</body>
</html>

问题是当浏览器的大小调整为更小并且一个框被敲到框下方的行时,框将向左点亮,而我希望它们始终居中。这可能使用纯 css 还是我需要使用一些 jquery?

4

4 回答 4

6

可能最简单的解决方案是从框中删除 float: left 样式并将显示属性更改为 inline-block。然后,您需要做的就是 text-align: center 在包装器上。

<html>
<head>
<title>Testing</title>
<style>
br.clear { clear:both; display:block; height:1px; margin:-1px 0 0 0; }
#wrapper { max-width: 960px; min-width: 320px; background: #444; margin: 0 auto; text-align:center }
.box { width: 280px; padding: 10px; margin:10px; height: 260px; border: 0px; background: #fff; display:inline-block }
</style>
</head>
<body>

<div id="wrapper">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <br class="clear" />
</div>

</body>

您可以在这里测试代码:http: //jsbin.com/uqamu4/edit

于 2010-10-12T10:03:58.563 回答
3

您可以text-align: center在包装器和display: inline-block框中使用,以使它们的行为类似于无论如何都居中的普通文本元素。

警告:不适用于 IE6 和 IE 7。适用于 Chrome 和 FF

JSFiddle在这里

于 2010-10-12T10:05:45.917 回答
0

对我有用的解决方案:

<style>
    body {
        /* To center the list */
        text-align: center;
    }

    #wrapper {
        /* To reset 'text-align' to the default */
        text-align: left;

        display: inline;
    }

    .box {
        display: inline-block;
    }
</style>
于 2014-07-13T18:50:49.927 回答
0

这在 ie 8 或更少的版本中不起作用,不知道 9,但是由于您使用max-width并且min-width其中不在那里工作,我还是会发布它。

<html>
<head>
<title>Testing</title>
<style>
br.clear { clear:both; display:block; height:1px; margin:-1px 0 0 0; }
#wrapper { max-width: 960px; min-width: 320px; background: #444; margin: 0 auto; text-align:center; }
.box { width: 280px; padding: 10px; margin:8px; height: 260px; border: 0px; background: #fff; display:inline-block;}

</style>
</head>
<body>

<div id="wrapper">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
    <br class="clear" />
</div>

</body>
</html>
于 2010-10-12T10:05:02.650 回答