user381800
user381800

Reputation:

jQuery center element to viewport using center plugin

I am currently using the jQuery center plugin to center my div element and so far it works to an extend where it does center it to the containing parent container. What I want it to do is to center it to the current browser viewport center. How can that be done?

My setup is a simple link when clicked, a div will pop up like a modal that I want centered into the current browser viewport center.

Upvotes: 2

Views: 6810

Answers (2)

Šime Vidas
Šime Vidas

Reputation: 185943

No plug-in is needed. This does the trick:

$('#yourElement').css('display', 'inline-block').wrap('<table style="position:fixed;top:0;left:0;height:100%;width:100%;border-spacing:0;border-collapse:collapse"><tr><td style="vertical-align:middle;text-align:center;padding:0"></td></tr></table>');

Live demo: http://jsfiddle.net/simevidas/EnrLn/1/


Same thing, but without the TABLE element. I use DIV's with display:table and display:table-cell instead:

Live demo: http://jsfiddle.net/simevidas/EnrLn/2/

Upvotes: 11

CoolEsh
CoolEsh

Reputation: 3154

Use

jQuery( "#element_id" ).css( 'top', parseInt( ( jQuery( window ).height() / 2 ) + jQuery( document ).scrollTop() - jQuery( "#element_id" ).height() ) );
jQuery( "#element_id" ).css( 'left', parseInt( ( jQuery( document ).width() / 2 ) + jQuery( document ).scrollLeft() - jQuery( "#element_id" ).width() ) );

Upvotes: 2

Related Questions