中心DIV内容流体垂直和水平

时间:2012-01-08 17:29:41

标签: html css xhtml margin fluid-layout

这是我的例子:

enter image description here

线高不适用于流体div。我的代码目前基于行高,但框的大小会发生变化。 那么如何才能让链接(内容)始终位于正中间?

我想确保此DIV中的内容始终从顶部和侧面均匀居中。垂直和水平居中。

当前代码:(注意样式标记为空白,因为这是动态填充的)

    <style type="text/css">
    .box{
    width:468px; /* php changes this sometimes */
    height:60px; /* php changes this sometimes */
    background:#eee;
    text-align:
    center;
    border:
    1px solid rgb(177, 172, 171);
    line-height: 61px;
    }
    </style>

    <div style="" class="box" id="">
<a style="color:#333;font-weight:bold" href="claimPrize();">Winner!</a>
</div>

1 个答案:

答案 0 :(得分:10)

不久前进入类似的情况,做了一次搜索,发现了一篇关于css-tricks绝对居中的文章,here是一篇文章,也是一个测试它的小提琴。

<强> CSS

/* This parent can be any width and height */
.block {
  text-align: center;
}

/* The ghost, nudged to maintain perfect centering */
.block:before {
  content: '';
  display: inline-block;
  height: 100%;
  vertical-align: middle;
  margin-right: -0.25em; /* Adjusts for spacing */
}

/* The element to be centered, can
   also be of any width and height */
.centered {
  display: inline-block;
  vertical-align: middle;
  width: 300px;
}

<强> HTML

<div class="block" style="height: 300px;">

    <div class="centered">
        <h1>Some text</h1>
        <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
    </div>

</div>

<div class="block" style="height: 200px;">

    <div class="centered">
        <h1>Some text</h1>
        <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
    </div>

</div>

<div class="block" style="height: 600px;">

    <div class="centered">
        <h1>Some text</h1>
        <p>But he stole up to us again, and suddenly clapping his hand on my shoulder, said&mdash;"Did ye see anything looking like men going towards that ship a while ago?"</p>
    </div>

</div>

演示

http://jsfiddle.net/andresilich/YqKMH/