2012-01-08 75 views
3

这就是例子,我有:中心DIV内容流体垂直和水平

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> 

回答

10

遇到类似的情况不久以前,做了搜索,发现了大约从CSS-技巧绝对中心的文章,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/

+0

什么宽度元素旧应用,也将这项工作呃浏览器? – TheBlackBenzKid 2012-01-08 17:44:39

+2

@TheBlackBenzKid由于使用了'text-align:center',div将始终位于容器的中间,而不管宽度如何。至于支持,由于':before'和':after'的伪选择器被IE7松散地支持,我会说支持IE8 +,尽管你可能在IE7中脱离它而需要测试。我会说IE8 +对于非JS方法听起来很划算:P。 – 2012-01-08 17:50:02

+0

辉煌的作品!令人惊叹的一段代码。这是我需要的很长时间的解决方案谢谢! – TheBlackBenzKid 2012-01-08 17:50:18