2016-09-24 117 views
0

我需要幫助將兩個div垂直居中放置在固定寬度/高度div中,其中兩個div在父div中間縮放。 第一個子div具有最大高度,因此它可以動態擴展一定程度。我怎樣才能讓它們居中,使青色和綠色的div在垂直方向上藍色?垂直居中兩個div

的jsfiddle位置:https://jsfiddle.net/850sdmhj/

.subtext-container { 
 
    position: absolute; 
 
    width: 180px; 
 
    height: 65px; 
 
    color: #ffffff; 
 
    background-color: blue; 
 
    bottom: 0; 
 
} 
 
.color-teal { 
 
    max-height: 40px; 
 
    overflow: hidden; 
 
    background-color: teal; 
 
} 
 
.color-green { 
 
    max-height: 13px; 
 
    font-size: 9px; 
 
    background-color: green; 
 
}
<div class="subtext-container"> 
 
    <div class="color-teal">teal</div> 
 
    <div class="color-green">green</div> 
 
</div>

+0

http://stackoverflow.com/questions/356809/best-way-to-center-a-div-on-a-page-vertically-and-horizo​​ntally可能的重複 – link2pk

回答

1

嘗試display:flex屬性,使其工作。

更新CSS:

.subtext-container { 
    position: absolute; 
    width: 180px; 
    height: 65px; 
    color: #ffffff; 
    background-color: blue; 
    bottom: 0; 
    display: flex; 
    justify-content: center; 
    flex-direction: column; 
} 

.color-teal { 
    max-height: 40px; 
    overflow: hidden; 
    background-color: teal; 
} 

.color-green { 
    height: 13px; 
    font-size: 9px; 
    background-color: green; 
} 

例小提琴Demo

注:請檢查瀏覽器的支持。

瀏覽器支持:http://caniuse.com/#feat=flexbox

0

使用以下CSS爲subtext-container

.subtext-container { 
    position: relative; 
    width: 180px; 
    height: 65px; 
    color: #ffffff; 
    background-color: blue; 
    bottom: 0; 
    display:table-cell; 
    vertical-align:middle; 
} 

更新小提琴https://jsfiddle.net/850sdmhj/1/

0

也許,通過使用類似於包裝

。顏色纏繞{ 位置:相對;頂部:50%; 變換:平移Y(-50%) }

.subtext-container { 
 
    position: absolute; 
 
    width: 180px; 
 
    height: 65px; 
 
    color: #ffffff; 
 
    background-color: blue; 
 
    bottom: 0; 
 
} 
 

 
.color-teal { 
 
    max-height: 40px; 
 
    overflow: hidden; 
 
    background-color: teal; 
 
} 
 

 
.color-green { 
 
    height: 13px; 
 
    font-size: 9px; 
 
    background-color: green; 
 
} 
 

 
.color-wrap{ 
 
\t position:relative; top:50%; 
 
\t -webkit-transform:translateY(-50%);-ms-transform:translateY(-50%);-o-transform:translateY(-50%);transform:translateY(-50%) 
 
}
<div class="subtext-container"> 
 
    <div class="color-wrap"> 
 
    <div class="color-teal">teal</div> 
 
    <div class="color-green">green</div> 
 
    </div> 
 
</div>

0

我會把。顏色,藍綠色和。顏色綠色另一次潛水內以「.vertical對齊」級。

<div class="subtext-container"> 
    <div class="vertical-align"> 
    <div class="color-teal">teal</div> 
    <div class="color-green">green</div> 
    </div> 
</div> 

然後在CSS文件:

.vertical-align{ /* This will do the trick to center content vertically */ 
    display: table-cell; 
    vertical-align: middle; 
} 

.subtext-container { 
    display: table; /* Add Display Table to the container */ 
} 

這將工作只有在容器(其中帶有顯示:臺)具有固定的高度。

您與工作示例小提琴:https://jsfiddle.net/rx79sb6m/

你也可以閱讀this post在這裏你可以找到另5種方法來達到同樣的效果。