2015-09-26 151 views
-6

這個問題也許之前被問過,但我的情況是某種特殊的。如何垂直居中元素?

我有兩個div在另一個裏面。兩個divs高度都是未知的,但我可以告訴外部div的是它的最小高度。重點是 - 如果內部div小於外部,我希望較小的div在外部div內垂直居中。如果內部div大於外部div的最小高度,我想讓內部div擴展外部div。

我想實現這一點,而不使用任何腳本。

這有可能嗎?

示例代碼:

<div id="outer" style="min-height:50px;"> 
    <div id="inner"> 
     Im here, I could be short, I could be long 
     and if I wrap - i could be tall 
    </div> 
</div> 
+4

是..現在你嘗試過什麼。堆棧溢出不是代碼寫入服務。 –

+3

http://howtocenterincss.com/可能有用 –

+0

不可能沒有腳本。另請提供示例代碼,以便我們看到並進行更改。 –

回答

1

使用display: tabledisplay: table-cellvertical-align: middle。繁榮。

現場演示:

.outer { 
 
    display: table; 
 
    min-height: 70px; 
 
    background-color: #BBB; 
 
    margin: 10px; 
 
} 
 
.inner { 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
}
<div class="outer"> 
 
    <div class="inner"> 
 
    Im here, I could be short, I could be long and if I wrap - i could be tall 
 
    </div> 
 
</div> 
 

 
<div class="outer"> 
 
    <div class="inner"> 
 
    <p>Im here, I could be short, I could be long</p> 
 
    <p>and if I wrap - i could be tall</p> 
 
    <p>Im here, I could be short, I could be long</p> 
 
    <p>and if I wrap - i could be tall</p> 
 
    </div> 
 
</div>

-1

基本上,沒有任何腳本(JS/jQuery的),這是不可能的。只有css,你不能說較小的div放在另一個裏面並垂直對齊。

正如你在你的問題中所說的那樣,關鍵字「if」解釋了它自己。對於你想要的,你必須使用一些腳本代碼。 Css只能聲明元素的樣式,而不是一個關於另一個的條件。

+1

這是100%可能沒有JS。請參閱這個問題的其他兩個答案。 –

1

你可以使用flexbox來做到這一點。看看這個jsFiddle

#outer { 
    display: flex; 
    align-items: center; 
    justify-content: center; 
} 

Here是一個有用的指南了flexbox