<!DOCTYPE HTML> <html lang="de"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Webseite horizontal und vertikal zentrieren</title> <link rel="stylesheet" type="text/css" href="css/page.css" /> </head> <body> <div id="page"> This is the centered content of the page. </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script src="js/page.js"></script> </body> </html>
html { font-size: 13px background: blue; } body { font-size: 100.1%; line-height: 140%; } #page { position: absolute; left: 50%; top: 50%; width: 920px; height: 560px; margin-left: -460px; /* half width*/ margin-top: -270px; /* half height */ color: white; background: red; background-image: linear-gradient(red 0%, black 100%); }
Nun würde man Teile von div#page nicht sehen, wenn das Browserfenster kleiner als der zentrierte DIV ist, da mit negativen margin-Werten gearbeitet wird – diese werden bei der Berechnung von Scrollbalken nicht beachtet. Um dem entgegenzuwirken kann man mit Hilfe von JavaScript die Fenstergröße überwachen und entsprechend den DIV neu positionieren.
// control the window-size and the left-/top-margin resp. -position of the #page var pageObj = {}, pageObjW = 0, pageObjH = 0, t = 0, l = 0, mt = 0, ml = 0, watchPageMinSize = function() { if ($(window).width() < pageObjW) { l = 0; ml = 0; } else { l = "50%"; ml = pageObjW / -2; } if ($(window).height() < pageObjH) { t = 0; mt = 0; } else { t = "50%"; mt = pageObjH / -2; } pageObj.css({ top : t, left : l, marginLeft : ml, marginTop : mt }); }; $(document).ready(function() { pageObj = $("#page"); pageObjW = pageObj.width(); pageObjH = pageObj.height(); watchPageMinSize(); }); $(window).resize(function() { watchPageMinSize(); });