В Интернете полно информации по выравниванию div’а по центру с помощью CSS, однако я не нашёл способов, которые бы всегда работали. Решил написать свой, получился плагин для jQuery.
Использование
Параметры
parent - относительно чего будет выравниваться элемент(пример: 'body', '#middle').
position - присваиваемая позиция, по умолчанию absolute
options - тип выравнивания: 'all', 'height', 'width', по умолчанию - 'all'
Код
(function($){
$.fn.center = function(parent, position, options) {
return this.each(function () {
var self = $(this);
self.css('position', (position != null) ? position : 'absolute');
if (parent == null)
{
width = self.parent().outerWidth();
height = self.parent().outerHeight();
}
else
{
width = $(parent).outerWidth();
height = $(parent).outerHeight();
}
if (self.parent().is('body') || parent == 'body') {
width = $(window).outerWidth();
height = $(window).outerHeight();
}
dwidth = self.outerWidth();
dheight = self.outerHeight();
if (options == 'width' || options == 'all' || options == null) {
self.css('left', (width - dwidth) / 2);
}
if (options == 'height' || options == 'all' || options == null) {
self.css('top', (height - dheight) / 2);
}
});
};
})(jQuery);