Saturday, October 8, 2011

Use Javascript to Center a Web Page web site was originally written using the margin-left and margin-right setting of auto to center it's pages. It worked as expected under Explorer 7 and Firefox 2. We could not get it to work correctly in Explorer 8 and Firefox 3 so we went back to basics.

In the old days before word processors, we took the width of a page and subtracted the width of the text and then divided by two and set the left margin to that number. Example: Left Margin = (Window Width - Fixed Design Width) / 2

Your web document needs a Block <div>Tag within the <body> tag. We gave ours an Id of Container. The two columns are floated left and right. The ChangeLeftMargin functions is called by <body onload="ChangeLeftMargin()">

Here is part of the code:

<script type="text/javascript">
< !--
function ChangeLeftMargin()
UserWidth = window.screen.width;
setWidth = (UserWidth - 700)/2;
StringSetWidth = setWidth + "px";
document.getElementById("container").style.marginLeft = StringSetWidth;
< /script>
< !-- #EndEditable -->
< /head>

<body onload="ChangeLeftMargin()">

<!-- Begin Container -->
< div id="container">

No comments:

Post a Comment