2017-02-21 125 views
-2

我想讓3個內容垂直出現在div的中心。我用vertical-align:middle,但它沒有做我想做的事情。我怎樣才能解決這個問題?垂直對齊div中的中心

我想讓home_post_time出現在垂直居中的右側角落。我嘗試過float:right;,但無法做到我想要的。這是我希望它出現

Image 
Image text    time 
Image 

.home_post_sections { 
 
    width: 100%; 
 
    height: 33%; 
 
    background-color: #01ff70; 
 
    text-align: left; 
 
} 
 

 
.home_post_propic { 
 
    width: 55px; 
 
    height: 55px; 
 
    margin-top: 5px; 
 
    margin-left: 5px; 
 
    margin-bottom: 5px; 
 
} 
 

 
.home_post_username { 
 
    margin-left: 20px; 
 
    width: 100%; 
 
    vertical-align: middle; 
 
} 
 

 
.home_post_time { 
 
    float: right; 
 
    vertical-align: middle; 
 
    text-align: right; 
 
    margin-right: 10px; 
 
}
<div className="home_post_sections"> 
 

 
    <img src="http://lorempixel.com/output/people-q-c-55-55-9.jpg" className="home_post_propic" /> 
 
    <a className="home_post_username">User name</a> 
 
    <a className="home_post_time">23h</a> 
 

 
</div>

+0

創建一個plunkr。 –

+2

@ManojLodhi沒有 - 在這裏創建一個片段!就像我使用'<>'按鈕 – mplungjan

+2

[垂直對齊圖像旁邊的文本?](http://stackoverflow.com/questions/489340/vertically-align-text-next-to-an-圖像) – mplungjan

回答

1

您可以使用此

<div style="display:flex;justify-content:center;align-items:center;"> 
<h1>Text In center</h1> 
</div> 

爲您的代碼

<div style="display:flex;justify-content:center;align-items:center;"> 

<img src="http://lorempixel.com/output/people-q-c-55-55-9.jpg" className="home_post_propic" /> 
<a className="home_post_username">User name</a> 
<a className="home_post_time">23h</a> 
</div> 
1

你可以使用Flex麥它垂直中心如下

<style> 
.home_post_sections{ 
    display : flex; 
    align-items : center; //make child items align vertically center 
} 
</style> 

<div className="home_post_sections"> 

    <img src="http://lorempixel.com/output/people-q-c-55-55-9.jpg" className="home_post_propic" /> 
    <a className="home_post_username">User name</a> 
    <a className="home_post_time">23h</a> 

</div> 
0

我做了主要的容器位置:相對; 我所做的時間容器位置:絕對;有50%的頂部和邊緣頂部減去其高度的一半。 10px只是一個近似值。

.home_post_sections { 
    position: relative; 
} 
.home_post_time { 
    position: absolute; 
    top: 50%; 
    right: 10px; 
    margin-top: -10px; 
} 

https://jsfiddle.net/1f09hp3f/

您已經使用大多是靜態的寬度和高度所以這個解決方案應該爲你工作,如果你只是想中心對齊一個元素。否則,您可以查看下面的鏈接以垂直對齊所有元素。 Vertical alignment of elements in a div