2012-01-08 78 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