2014-07-02 70 views
-2

我有一個div,高度en寬度爲33.33%。我想要div中的文字。在百分比高度的div中居中文本

HTML

<div class="blogs" id="content"> 
    <div id="blog1">tests</div> 
    <div id="blog2"></div> 
    <div id="blog3"></div> 
</div> 

CSS

#blog1 { 
    width: 33.33%; 
    padding-bottom: 33.33%; 
    background: red; 
    float: left; 
} 

enter image description here 我怎樣才能使這個?

+0

你的意思是垂直排列或水平排列的?我假設你是指垂直,因爲你指定的高度? – Blunderfest

+0

http://www.onenaught.com/posts/201/use-css-displaytable-for-layout – Sturm

+0

http://css-tricks.com/vertically-center-multi-lined-text/ – Thaddius

回答

1

我的建議是:

HTML

<div class="blogs" id="content"> 
    <div id="blog1">text in the middle 
     <span>blog 1</span> 
    </div> 
    <div id="blog2"><span>blog 2</span></div> 
    <div id="blog3"><span>blog 3</span></div> 
</div> 

CSS

#blog1{ 
     width: 33.33%; 
     /*padding-bottom: 33.33%;*/ 
     background: red; 
     text-align: center; 
     display:table-cell; 
     vertical-align:middle; 
     position: relative; 
    } 

.blogs > div > span{ 
    position: absolute; 
    bottom: 0px; 
    width: 100%; 
    left: 0px; 
} 
#blog2{ 
     width: 33.33%; 
     padding-bottom: 33.33%; 
     background: green; 
     text-align: center; 
     display:table-cell; 
     position: relative; 
    } 
#blog3{ 
     width: 33.33%; 
     padding-bottom: 33.33%; 
     background: blue; 
     text-align: center; 
     display:table-cell; 
     position: relative; 
    } 

#content{ 
    display:table; 
} 

fiddle

另一個具有靜態寬度例如500pxfiddle

+0

英雄!謝謝,謝謝! –

+0

不客氣:) –

0
<div class="blogs" id="content"> 
    <div id="blog1">tests</div> 
    <div id="blog2"></div> 
    <div id="blog3"></div> 

    <!-- You need to add this after the last <div> --> 
    <div style="clear:right;"></div> 
</div> 

#blog1, #blog2, #blog3 { 
    float:left; 
    padding: 3% 0; 
    background: red; 
    width: 100px; 
    height:100%; 
    text-align:center; 
} 

JS Fiddle

+0

寬度和hight必須是33.33% –

+0

你想讓它們成爲#content div大小的三分之一嗎?編輯博客div的大小是最簡單的部分。雖然解決了處於中心的文本部分。 – Lance

1

看一看這個​​

只需設置heightline-height平等,並添加vertical-align:middle;

您的代碼將是這樣的:

#blog1{ 
    width: 33.33%; 
    height:300px; 
    background: red; 
    float: left; 
    text-align:center; 
    vertical-align:middle; 
    line-height:300px; /* has to bee the same value as the height of the div */ 
} 
+0

寬度和高度必須是33.33% –