The vertical center of the HTML element within the dynamic height div

Possible duplicate:
vertical-align: medium not working

How can I make sure that <a></a> has a vertical orientation in this div, regardless of the size of the div:

http://jsfiddle.net/XF9WM/

thanks

+2
source share
5 answers

Using display:table and display:table-cell , which works in all modern browsers (IE 8 +):

 .post { width: 200px; height: 200px; background: rgba(0,0,0,0.8); display:table; } .post h2 { text-align: center; width: 100%; height: 100%; display:table-cell; vertical-align: middle; } .post h2 a { color: #f7f7f7; font-size: 2.2em; font-weight: normal; font-style: italic; width: 100%; } 
+4
source

I wanted to achieve this in a different way (just for fun), and this one also works: jsFiddle

The idea is to use the :before element at 50% height.

 html, body{ height:100%; } .post { width: 400px; height: 300px; background: rgba(0,0,0,0.8); } .post h2:before{ content:""; display:block; height:50%; } .post h2 { text-align:center; height:100%; } .post h2 a { color: #f7f7f7; font-size: 2.2em; margin-top:-20px; display: block; } 

Hope this helps :-)

+2
source

[UPDATED]

You can also do it like this: jsFiddle

 .post { width: 400px; height: 200px; background: rgba(0,0,0,0.8); position:relative; } .post h2 { position:absolute; top:50%; width:100%; text-align:center; } .post h2 a { line-height:100%; color: #f7f7f7; font-size: 2.2em; margin-top:-20px; display: block; } 
+1
source

Give your line a line height greater than the text will ever be, and vertically align it in the middle. Then absolutely put it parent in the div on top: 50% and the top margin at the top minus half the link-height line:

jsFiddle

 .post { position: relative; } .post h2 { text-align: center; width: 100%; position: absolute; top: 50%; margin-top: -150px; } .post h2 a { vertical-align: middle; line-height: 300px; white-space: nowrap; } 

It even works in IE7.

+1
source

If you don't mind adding an extra HTML class, your easiest way is to simply use vertical alignment: medium.

http://jsfiddle.net/Wexcode/HtNJM/

 <div class="post"> <span></span><h2><a href="#">Hello!</a></h2> </div> 

CSS

 * { margin: 0; padding: 0; } .post { background: rgba(0,0,0,0.8); width: 200px; height: 200px; } .post span { height: 100%; vertical-align: middle; display: inline-block; } .post h2 { position: relative; text-align: center; width: 100%; vertical-align: middle; display: inline-block; } .post h2 a { color: #f7f7f7; font-size: 2.2em; font-weight: normal; font-style: italic; display: block; } 
0
source

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


All Articles