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

+2

@TheBlackBenzKidは 'text-align:center'を使うため、divは幅にかかわらず常にコンテナの中央にあります。サポートについては、 ':before'と':after'の擬似セレクタがIE7によって緩やかにサポートされているので、サポートはIE8 +ですが、おそらくIE7で諦めることができます。私はIE8 +がJS以外のアプローチのための良い案のように聞こえると言うでしょう:P。 –

+0

華麗な作品!驚くべきコード。これは私が必要とした長い時間の解決でしたありがとう!! – TheBlackBenzKid

関連する問題