jQuery center element to viewport using center plugin

匆匆过客 提交于 2019-12-02 05:45:36

问题


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.


回答1:


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/




回答2:


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() ) );


来源:https://stackoverflow.com/questions/5281112/jquery-center-element-to-viewport-using-center-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!