[英]Vertical align text inside dynamic height div
I want to vertically align text inside a div which is dynamic height say 10% of page for example, but without using the well-known "table method". 我想在div内垂直对齐文本,该div是动态高度,例如说占页面的10%,但不使用众所周知的“表格方法”。 Can this be achieved with pure CSS? 可以使用纯CSS来实现吗?
Piece of code: 代码段:
HTML: HTML:
<div class="post-details-wrapper">
<div class="post-details-h">
Post Details
</div>
</div>
CSS: CSS:
post-details-h {
background-color: green;
height:5%;
width:100%;
}
In this particular case the goal is to vertically align the text of "post-details-h" div. 在此特定情况下,目标是垂直对齐“ post-details -h” div的文本。
use display: flex
+ align-items: center
使用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>
The usual approach is to use display:table stuff. 通常的方法是使用display:table的东西。 But if you don't want to use it, you can try something like this: 但是,如果您不想使用它,可以尝试如下操作:
<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;
}
Just add span so you can center taht element inside .post-details-h. 只需添加跨度,即可将taht元素放在.post-details-h中。
You can check in JSFiddle 您可以签入JSFiddle
Hope this helps. 希望这可以帮助。
Check out this fiddle . 看看这个小提琴 。 The way that I know how to do it does involve two classes, like how you did it. 我知道该怎么做的方式确实涉及到两个类,就像您的工作方式一样。
.post-details-h {
line-height: 200px;
width:100%;
vertical-align: center;
}
.post-details-wrapper {
background-color: red;
height: 200px;
position: relative;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.