Home > Article > Web Front-end > How to Center a Popup Window in the Browser?
How to Position a Popup Window Precisely in the Center of the Screen
Centering a popup window created using JavaScript's window.open function on the screen is essential for optimal user experience. The exact coordinates depend on the screen resolution, so a dynamic solution is required.
Solution: Utilize a Single/Dual Monitor Function
A robust solution that accommodates both single and dual monitor setups is given below:
<code class="javascript">const popupCenter = ({ url, title, w, h }) => { // Determine the positions based on screen resolution const dualScreenLeft = window.screenLeft || window.screenX; const dualScreenTop = window.screenTop || window.screenY; const width = window.innerWidth || document.documentElement.clientWidth || screen.width; const height = window.innerHeight || document.documentElement.clientHeight || screen.height; // Adjust for system zoom const systemZoom = width / window.screen.availWidth; // Calculate the centered coordinates const left = (width - w) / 2 / systemZoom + dualScreenLeft; const top = (height - h) / 2 / systemZoom + dualScreenTop; // Open the popup window with the calculated dimensions and positioning const newWindow = window.open(url, title, ` scrollbars=yes, width=${w / systemZoom}, height=${h / systemZoom}, top=${top}, left=${left} ` ); if (window.focus) newWindow.focus(); };</code>
Usage Example:
<code class="javascript">popupCenter({ url: 'http://www.xtf.dk', title: 'xtf', w: 900, h: 500 }); </code>
Credits and Source:
This solution, originally from http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html, effectively handles popup window centering for a variety of screen configurations.
The above is the detailed content of How to Center a Popup Window in the Browser?. For more information, please follow other related articles on the PHP Chinese website!