Div中的元素

时间:2013-08-15 20:22:08

标签: css html center

我有一个div,元素需要居中:

<div style="width:800px;margin:0 auto;color:#000;"><h3 style="float:left;color:#000;margin:0 10px;"> Test </h3><h4 style="float:left;padding-top:3px;"> | </h4><h3 style="color:#000;float:left;margin:0 10px;"> Test </h3></div>

然而,所有元素都只留在左边。我如何解决这个问题并将所有h3和h4都集中在一起?

以下是我的示例:http://approvemyride.ca/reno/

2 个答案:

答案 0 :(得分:2)

http://jsfiddle.net/ZeJdc/

HTML:

<div>
    <h3> Test </h3>
    <h4> | </h4>
    <h3> Test </h3>
</div>

CSS:

div {
    width: 800px;
    margin: 0 auto;
    color: #000;
    text-align: center;
}

h3 {
    color: #000;
    margin: 0 10px;
    display: inline-block;
}

h4 {
    padding-top: 3px;
    display: inline-block;
}

检查出来并让我知道你的想法,如果它在你第一次打开时没有看起来居中,请尝试向左拉伸小分隔线,为结果窗格提供更多空间。

为了澄清,display:inline-block允许所有标题显示在同一行,而text-align:center<div>内所有标题元素的中心。

答案 1 :(得分:0)

每当我面对任何浮动的容器水平居中时,我都会使用以下内容。尝试将您的标记(需要居中;在您的案例中为div)包装起来:

<div class="center_outer">
    <div class="center_inner">
        <!-- Put your contents here (which needs to be centered) -->
    </div>
</div>

CSS:

.center_outer
{
    position: relative;
    left: 50%;
    float: left;
}
.center_inner
{
    position: relative;
    left: -50%;
}

检查:http://jsfiddle.net/jduDD/1/(我已移除width样式)