Center a div with unknown height vertically

Well, I know that they asked him several times, but I did not find a cross-browser solution and did not understand it. :-(

I have this code to scale the video to 100% of the browser width:

<div id="flashposition"><div id="flashvimeo"class="vimeo">HereIsTheVideo</div></div> 

and this css:

 #flashposition { position: relative; padding-bottom: 56.25%; /* 16:9 */ padding-top: 0px; height: 0; z-index:30; display: block; overflow:hidden; } #flashvimeo object, embed { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } 

It works, but it cuts off the excess height at the bottom, but I would like it to be centered, so the excess height of the video is cut halfway up and down.

Any ideas that are safe and also work in IE7? Or is this the only way to do this in js / jquery and recalculate the height / width due to the size of the browser window, as here http://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php ?

+8
javascript jquery css
source share
4 answers

Unfortunately, there is no elegant cross-browser, backward compatible solution without a script.

However, CSS3 supports box-flex with box-orient: horizontal; which is designed to do exactly what you want. Browser support for CSS3 is still a bit thin on the ground, so if you want a solution that works for everyone, you will need to use the window resize event and layout with a script.

HTML 5 Rocks - flexbox

+6
source share

This answer may be disgusting, but I found that a simpler and cross-browser way to vertically center any element in html / css is to use table elements. Another way is to use JS to calculate the height of the container and then position it.

+5
source share

This trick is pretty good: http://css-tricks.com/centering-in-the-unknown/

 /* This parent can be any width and height */ .block { text-align: center; } /* The ghost, nudged to maintain perfect centering */ .block:before { content: ''; display: inline-block; height: 100%; vertical-align: middle; margin-right: -0.25em; /* Adjusts for spacing */ } /* The element to be centered, can also be of any width and height */ .centered { display: inline-block; vertical-align: middle; width: 300px; } 
+4
source share

All Articles