垂直对齐动态高度内的文本 div

Vertical align text inside dynamic height div

我想垂直对齐 div 内的文本,动态高度例如占页面的 10%,但不使用众所周知的 "table method"。这可以用纯 CSS 来实现吗?

一段代码:

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%;
}

在这种特殊情况下,目标是垂直对齐 "post-details-h" div.

的文本

使用 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>

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

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

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

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

<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;
}

只需添加 span 即可将 taht 元素置于 .post-details-h.

您可以签到JSFiddle

希望对您有所帮助。