Skip navigation


How to Center a Layer

by Ryan Frishberg

To center a layer, we'd need to find the screen size (innerWidth) of the page and the width of the layer.
Then just subtract the width of the layer from the width of the page. And dividing by two splits that "left over space" into half so that the left side of the layer will have half of it on its side and the same with the right side of the layer. Go to fast for you? Consider the following diagram:

Let's look at an example now:



The Code

And here's the code:

<script>
      var IW=window.innerWidth ? window.innerWidth : document.body.clientWidth;

      function accessCSS(layerID){
            if(document.getElementById){
                  return document.getElementById(layerID).style;
            }else if(document.all){
                  return document.all[layerID].style;
            }else if(document.layers){
                  return document.layers[layerID];
            }
      }

     function getLayerWidth(layerID){
           if(document.getElementById){
                 return parseInt(document.getElementById(layerID).offsetWidth);
           }else if(document.all){
                 return parseInt(document.all[layerID].offsetWidth);
           }else if(document.layers){
                 return parseInt(document.layers[layerID].clip.width);
           }
     }

     function centerLayer(layerID){
           accessCSS(layerID).left = (IW - getLayerWidth(layerID))/2;
     }
</script>

<div id="myLayer1" style="position:absolute;top:170px;left:30px;z-index:3; height: 25px"><a href="javascript:centerLayer('myLayer1')">Center this layer</a></div>

This is fairly straightforward, so I'm not going to explain it. Note that centering a layer does not require defining its width.

Let's move on to another cool feature of DHTML, writing new content to layers.

Next -->