2015-08-14 79 views
1

我想垂直对齐文本里面的动态高度说例如10%的页面,但没有使用众所周知的“表方法”。这可以通过纯CSS实现吗?垂直对齐动态高度div内的文本

enter image description here

一段代码:

HTML:

<div class="post-details-wrapper"> 
    <div class="post-details-h"> 
     Post Details 
    </div> 
</div> 

CSS:

post-details-h { 
background-color: green; 
height:5%; 
width:100%; 
} 

在这种特殊情况下,我们的目标是垂直对齐“后的文本-details-h“div。

回答

1

通常的做法是使用display:table stuff。但是,如果你不想使用它,你可以尝试这样的事:

<div class="post-details-wrapper"> 
    <div class="post-details-h"> 
     <span>Post Details</span> 
    </div> 
</div> 

.post-details-wrapper { 
    height:350px; 
    background:red; 
} 
.post-details-h { 
    background-color: green; 
    height:10%; 
    width:100%; 
} 
.post-details-h:before { 
    content: ''; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
} 
.post-details-h span { 
    display: inline-block; 
    vertical-align: middle; 
} 

只需添加跨度,以便可以在里面居中taht元素。员额,细节小时。

您可以检查JSFiddle

希望这有助于。

+0

这种方法非常完美! – sarotnem

1

使用display: flex + align-items: center

*{ 
 
    padding: 0; 
 
    margin: 0; 
 
} 
 

 
.post-details-h{ 
 
    background-color: green; 
 
    height: 100px; 
 
    width: 100%; 
 
    display: flex; 
 
    align-items: center; 
 
}
<div class="post-details-wrapper"> 
 
    <div class="post-details-h"> 
 
     <span>Post Details</span> 
 
    </div> 
 
</div>

+0

好的解决方案,很好地完成。 –

+0

很好的解决方法,但存在跨浏览器兼容性问题。与Chrome和Firefox完美兼容,但在Safari中并不是 – sarotnem

0

看看这个fiddle。我知道如何去做的方式确实涉及到两个类,就像你做过的那样。

.post-details-h { 
    line-height: 200px; 
    width:100%; 
    vertical-align: center; 
} 

.post-details-wrapper { 
    background-color: red; 
    height: 200px; 
    position: relative; 
} 
+0

但是在这种情况下,高度是固定的 – sarotnem

+0

是的,这是真的。我知道你可以像'line-height:500%;'那样使用'line-height',但这是一个可怕的黑客攻击,我不会推荐它。也许如果我用小提琴演奏更多的东西,我可以想出一些东西。 – UltraSonja