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". Can this be achieved with pure CSS?
Piece of code:
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%;
}
In this particular case the goal is to vertically align the text of "post-details-h" div.
use 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. 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.
You can check in 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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.