Vertically center text inside an absolutely positioned div

I am trying to vertically center text inside a div that is positioned absolutely.

I tried the table-cell approach with no luck. This is a responsive layout, so I try to avoid setting fixed heights and prefer not to use Javascript.

thanks

Link to jsbin demo

HTML and CSS:

 <div class="page-banner" style="background: url(http://www.bimga.com.php53-3.ord1-1.websitetestlink.com//wp-content/uploads/BIMGA_Website_InteriorPage_Banners_About.jpg) no-repeat scroll 0 0 / cover transparent"> <img style="visibility:hidden" src="http://www.bimga.com.php53-3.ord1-1.websitetestlink.com//wp-content/uploads/BIMGA_Website_InteriorPage_Banners_About.jpg"> <div class="left"> <div class="page-banner-text">this text needs to be verticall centered</div> </div> </div> <style type="text/css"> .page-banner { margin-bottom: 35px; list-style: none; width: 100%; padding-left: 0; position: relative; } .page-banner img { width: 100%; height: auto; } .page-banner .left { background-color: rgba(10, 65, 142, .75); position: absolute; z-index: 1; left: 0; top: 0; height: 100%; text-align: center; width: 50%; } </style> 
+6
source share
3 answers

We could use transform like this:

You have jsBin!

CSS

 .page-banner-text { top: 50%; transform: translateY(-50%); position: absolute; } 

Additional information on this technique.

+3
source

What you can do is set the absolute position of the text. Then give him the upper hand: 50%; and give it the top edge minus half its height.

+1
source

I would prefer to use the absolute position and the top: 50% for better support for multiple browsers (for example, in older versions of IE), so I would prefer to add the line height: x em; in your class .page banner. Em, because you determined the height by%, so it should always be in the center, regardless of the actual pixel height.

 .page-banner .left:after { content: "Background text"; position: absolute; top: 40%; left: 35%; z-index: -1; } 
0
source

Source: https://habr.com/ru/post/973496/


All Articles