2017-02-21 126 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