Vertical alignment without knowing height in CSS?
I would normally use absolute positioning and set the top to 50% with a negative margin-top (half of the child's height) to center vertically. In this case that will not work because the child element's height will vary.
So is there a way to vertically center a div within a div without knowing the child's height?开发者_开发问答
The following jquery function centers vertically assuming the item you are positioning is already position absolute and the parent position relative
$.fn.vAlign = function () {
return this.each(function () {
$(this).css('top', '50%').css('margin-top', -Math.ceil($(this).height() / 2) + "px");
});
};
View in action - http://jsfiddle.net/vqbMU/2/
UPDATE:
A pure CSS solution for browsers supporting css transforms (IE9+) http://caniuse.com/#search=transform
.align-v {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
You can make the element display: table-cell and put vertical-align:center. I don't usually recommend using display: table- but that's the easiest solution I think
You can also grab the child's height easily enough with JavaScript dynamically, and even easier with a JS library like jQuery.
According to your profile, you do have some familiarity with jQuery, so I would suggest that route. If you need help with that solution let me know.
Use padding top , padding bottom to center elements vertically , with or without height definitions ...
精彩评论