居中一个CSS盒子?

时间:2013-12-01 00:31:06

标签: html css

HTML:

<div class="cont">
    <center>
        <div class="xmdiv">
            <img class="xmenu" src="media/file1.png">
            <img class="xmenu" src="media/file2.png">
        </div>
    </center>
    <p>-snip-</p>
</div>

CSS

.cont {
        position: relative;
        margin-top: 3%;
        background-color: transparent;
        width: 65%;
        -moz-border-radius: 3px;
        -webkit-border-radius: 3px;
        border-radius: 1px;
        -moz-box-shadow: 0px 0px 11px #000000;
        -webkit-box-shadow: 0px 0px 11px #000000;
        box-shadow: 0px 0px 11px #000000;
        font-family: 'Open Sans', sans-serif;
        color: #070707;
        font-size:15px;
        font-weight:300;
        text-align:justified;
        line-height:1.5;
}
p {
    margin-left: 8px;
    margin-right: 8px;
}

它看起来像什么: enter image description here

我希望它居中,我该怎么做?尝试在网上查找它并没有真正起作用。

3 个答案:

答案 0 :(得分:1)

要使div(以及许多其他类型的元素)居中,请使用此CSS代码:

.cont { 
   margin: 0 auto;
   width: XXXpx;
}

JSFiddle.

确保指定宽度,否则div不会居中。

修改

要在不指定的情况下居中元素,您可以执行以下操作(但不确定这是否适用于所有浏览器):

body { text-align:center; }
.cont { display:inline-block; }

边注

不要使用中心标记,不推荐使用。您可以阅读更多相关信息here

答案 1 :(得分:1)

这是你想要的吗?链接:http://jsfiddle.net/jtFUs/

<强> CSS:

.cont
{
    position: relative;
    margin: 0 auto;
}

答案 2 :(得分:1)

如果您需要在页面上垂直和水平居中div,请使用:

div {
    width: 100px;
    height: 100px;
    background-color: #000000;

    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;

    margin: auto;
}

http://jsfiddle.net/65adr/48/

如果您需要水平居中,请使用:

center
{
  width: 200px;
  display: block;
  margin-left: auto;
  margin-right: auto;
}

只需定义元素的宽度,在本例中我添加了200px。

http://jsfiddle.net/65adr/50/