Resize / reposition divs and and background based on window size

One problem that I’ve run into is positioning/sizing divs on a background, with the following caveat:  when the window is resized, the background is resized…however, the divs don’t adjust accordingly.  Well here’s how to accomplish that.

First let’s create our HTML file.

<html>
  <head>
    <link rel="stylesheet" href="ourStyle.css" type="text/css" media="screen"/>
  </head>
  <body>
    <div id="page-background">
      <img src="ourBackground.png" id="bgimg" alt="Our Background"/>
    </div>

    <div id="contentBlock1">
      Some content goes here
    </div>
  </body>
</html>

ourStyle.css

html, body {height:100%; margin:0; padding:0;}
#page-background { /* sets background to full width and height of browser window */
 position:fixed;
 top:0;
 left:0;
 width:100%;
 height:100%;
 }
#contentBlock1 {
 position:relative;
 top: 51.42%;   /* use percentages for the top,left to maintain the top-left corner at the same */
 left: 48.66%;  /* relative position on the background */
 width: 26.69%;    /* use % for width,height to scale the div block according to the window */
 height: 23.57%;   /* width and height */
 background: #999999;
 z-index:1;
 padding:10px;
 }

What’s Happening?

Say you have an image that’s 1120 x 700 at 100% view.  Now let’s say you find that you have a part of the background that you want to place a div over, say for a nav bar.  First, open the image in some editing program that will show you the pixels/points that your mouse is hovering over, and find the top-left corner of the space you want to place your nav bar.  That should give you two points:  x1 , y1.

Next, hover your mouse over the bottom-right corner of where your nav bar will be.  This should give you points:  x2 , y2.

So let’s say in my image, my top-left corner is at:  ( 545 , 360 )  and my bottom-left corner: ( 844 , 525 ).

x1 = 545 ,  x2 = 844

y1 = 360 ,  y2 = 525

Now to find the values:

top   = y1  / 700
      = 360 / 700 = 0.5143

left  = x1  / 1120
      = 545 / 1120 = 0.4866

width =  (x2 - x1)  / 1120
      = (844 - 545) / 1120 = 0.2669

height=  (y2 - y1)  / 700
      = (525 - 360) / 700 = 0.2357 

Now, since we’re working in PERCENTAGES, we need to multiply those values by 100.  Thus, our result is:

top: 51.42%;
left: 48.66%;
width: 26.69%;
height: 23.57%;

Which, if we look at ourStyle.css, are the values that were used there.

Hope this finds use for someone.

Until next time,
dVz-

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s