user3722555
user3722555

Reputation: 1

How to dynamically calculate the positioning width of a fixed div element using the width of browser and width of the body

I'm using the following CSS Styling for two div's that will place skyscraper ad's on my website to the left and right of the body.

/*-----Sky Scraper ad----*/
#SkyAdLeft{
 width: 160px;
 display: block;
 position: fixed;
 top: 100px;
 left: 10px;
  height: 600px;
 z-index: 7;
}
#SkyAdRight{
 width: 160px;
  display: block;
 position: fixed;
 top: 100px;
 right: 10px;
 height: 600px;
 z-index: 7;
}

I want each DIV to remain fixed however I want to dynamically calculate the left position in the left ad and the right positioning in the right ad to be able to sit 10px left or right of the body.

With my body always being 980px and centered I figured out the math to do this based on browser width. My Ad's are 160px in width.

Width Calc for Left AD:

(Browser width - 980) / 2 = X

(Browser Width - (160 + X + 980)) -10

Width Calc for Right Ad:

(Browser width - 980) / 2 = X

(Browser width - X) +10

Calculations explained: I am subtracting the body width of 980 from the dynamic browser width then dividing by 2 to get the value of the empty spaces between the end of my browser and the end of my body. This is where the ads with sit.

The second calculation for each respective ad then calculates where the ad should be positioned within the browser screen.

The right ad is simple. It's the Browser width minus X which is the empty space value form the first calculation. Then add 10px. This will set the ad 10x to the right of the body.

The second calculation for the left ad is more complicated but also will set the left ad 10px to the left of the body.

How do I use jquery or javascript to do these calculations and where do I run the jquery? In the css styling file or in my footer.php file where the div's are in the code?

Also if anyone knows a quicker solution to this problem that will allow my div's to sit 10px left or right of the body. Please let me know.

Upvotes: 0

Views: 7120

Answers (1)

Paulie_D
Paulie_D

Reputation: 115293

If I understand you correctly, you want the Ads to sit 10px away from the centered "container" (not the body).

If so, it's just a matter of positioning each ad 50% away from it's respective side and the adjusting the margins

Codepen Demo

**HTML**

<div class="Ad left">

</div>

<div class="Ad right">

</div>

<div class="container">

</div>

CSS

.container {
  width:980px;
  margin: 0 auto;
  height:500px;
  background-color: grey;
}

.Ad {
  width: 160px;
  display: block;
  position: fixed;
  top: 10px;
  height: 600px;

}

.left {
  left: 50%;
  background-color: orange;
  margin-left: calc(-160px - (980px/2) - 10px);
  /* element width + 50 % of container width + required distance */
}


.right {
  right:50%;
  background-color: purple;
  margin-right: calc(-160px - (980px/2) - 10px);
}

Upvotes: 2

Related Questions