Software, your way.
burger menu icon
WillMaster

WillMaster > LibraryWebsite Development and Maintenance

FREE! Coding tips, tricks, and treasures.

Possibilities weekly ezine

Get the weekly email website developers read:

 

Your email address

name@example.com
YES! Send Possibilities every week!

Responsive Fixed and Absolute Centering

Centering a div, floating on top of other content, can be a challenge for responsive pages. The position of the div needs to be recalculated whenever the screen is resized or its orientation is changed.

As examples, floating divs centered on the page can be used for a site operations notice, subscription form, note of appreciation, or promotion.

I'll describe how to center floating content, horizontally and vertically, on any size screen. It re-centers whenever the screen is resized or the device orientation is changed.

The div is centered with JavaScript. In order for the JavaScript to accomplish the centering, the div needs to have either the CSS rule position:fixed or the CSS rule position:absolute.

The difference between the effect of the CSS rule position:fixed and the CSS rule position:absolute are:

  • When the position:fixed; div is centered, it's centered in the browser window at whatever scroll position exists at the moment. The position of the div remains fixed and visible in the browser window even if the content is scrolled.

  • When the position:absolute; div is centered, it's centered as if the content were scrolled all the way to the top. The div scrolls with the content and becomes invisible or hidden if the content is scrolled down far enough.

To see the difference, try it both ways on your test page. The only change is the value of the CSS postion property, changed from "fixed" to "absolute" or vice versa.

To implement responsive fixed and absolute centering, do these 3 steps:

  1. Create the div to be centered.

  2. Paste the JavaScript into the web page source code.

  3. Modify the JavaScript in one spot, where you provide the id value of the div created in step 1.

Full instructions, with source code, are in the Implementation section.

The div will position itself when the page is loaded. If the screen dimensions are changed, the div will reposition. If the page is in a device, the div will reposition whenever the device's orientation is changed.

Implementation

Here are the full implementation instructions with examples and source code.

1. Create the div to be centered.

It's a regular div with six required CSS properties: "position", "left", "top", "width", "height", and "z-index". Here's an example (notes follow):

<div 
   id="my-div" 
   style="
      position:absolute; 
      left:0; 
      top:0; 
      width:100px; 
      height:100px; 
      z-index:25; 
   ">
[Content for div goes here]
</div>

Notes:

The div must have an id value. In the above example, the id value is colored blue.

The position property value can be either "absolute" or "fixed". The example (colored red) is specified as "absolute".

The left and top property values need to be "0". When the div is adjusted, the JavaScript changes those values.

The width and height property values need to be the width and height that's appropriate for your div.

The z-index property value needs to be higher than any z-index value of the content the div is to float on top of. Default z-index value is 1. Therefore, z-index:2; might be sufficient.

(The example has z-index:25; because it's unlikely any regular content has a z-index value that high. If needed for your implementation, change 25 into a larger number.)

Paste the sourced code of the div into your test page anywhere in the BODY area.

2. Paste the JavaScript into the web page source code.

The JavaScript is in the box below. It may be pasted anywhere in the source code or imported from an external file.

<script style="text/javascript">
// Will Bontrager Software LLC
// https://www.willmaster.com/
function doResponsiveCentering()
{
   /* Customize next line. */
   var IDofDiv = "my-div"; // Specify id value of fixed/absolute div to center.
   /* Customize above line. No other customization required.*/
   var pointer = document.getElementById(IDofDiv);
   var DivWidth = pointer.offsetWidth;
   var DivHeight = pointer.offsetHeight;
   if(document.documentElement && document.documentElement.clientWidth)
   {
      pointer.style.left = parseInt((document.documentElement.clientWidth-DivWidth)/2) + "px";
      pointer.style.top = parseInt((document.documentElement.clientHeight-DivHeight)/2) + "px";
   }
   else if(document.body)
   {
      pointer.style.left = parseInt((document.body.clientWidth-DivWidth)/2) + "px";
      pointer.style.top = parseInt((document.body.clientHeight-DivHeight)/2) + "px";
   }
   else
   {
      pointer.style.left = parseInt((window.innerWidth-DivWidth)/2) + "px";
      pointer.style.top = parseInt((window.innerHeight-DivHeight)/2) + "px";
   }
}
window.addEventListener('DOMContentLoaded', doResponsiveCentering);
window.addEventListener('load', doResponsiveCentering);
window.addEventListener('resize', doResponsiveCentering);
window.addEventListener('orientationchange', doResponsiveCentering);
</script>

3. Modify the JavaScript in one spot.

At the seventh line from the top of the above JavaScript code, you'll see the place that needs to be customized. It's colored blue.

Replace the my-div id value with the id value you provided for the div you created in step 1.

You now have an automatically centering floating div. Centered content, horizontally and vertically, responsive to screen size and orientation change. It re-centers whenever the screen is resized or the device orientation is changed.

Example floating div centered on the screen. Click here to close box.
X

But there's one more thing.

Closing the Box

To let the user close the box, the div needs to have a CSS display property. The link to close the div can be (where "my-div" is the id value of the centered floating div):

<span style="cursor:pointer; color:blue; text-decoration:underline;" onclick="document.getElementById('my-div').style.display='none'">Click here</span>

Here's the code for the demonstration centered floating div you saw when you first loaded this page:

<div 
   id="my-div" 
   style="
      position:fixed; 
      left:0; 
      top:0; 
      width:200px; 
      height:60px; 
      z-index:25; 
      display:block; 
      background-color:ivory;
      border:3px solid beige;
      border-radius:12px;
      padding:10px;
   ">
Example floating div centered on the screen. 

<!-- (for the "Click here" link) -->
<span style="cursor:pointer; color:blue; text-decoration:underline;" onclick="document.getElementById('my-div').style.display='none'">Click here</span> to close box.

<!-- (for the "X" link in the upper-right corner) -->
<div style="position:absolute; top:5px; right:5px; cursor:pointer; color:blue; font-weight:bold; border:1px solid blue; border-radius:50%;" onclick="document.getElementById('my-div').style.display='none'">X</div>

</div>

Advanced Techniques

The code as described in this article places a div centered on the screen floating on top of regular page content. The div is displayed immediately after the rest of the content has finished loading.

Although detailed instructions are outside the intended scope of this article, here's a synopsis of how to delay the appearance of the div.

To delay the appearance of the centered floating div:

  • Give the centered floating div a CSS rule display:none.

  • Create JavaScript to change the display to "block" after so many seconds — or when the user clicks on a link or some other event happens, such as a window scroll.

Now, you're good to go :)

(This article first appeared in Possibilities ezine.)

Will Bontrager

Was this article helpful to you?
(anonymous form)

Support This Website

Some of our support is from people like you who see the value of all that's offered for FREE at this website.

"Yes, let me contribute."

Amount (USD):

Tap to Choose
Contribution
Method

All information in WillMaster Library articles is presented AS-IS.

We only suggest and recommend what we believe is of value. As remuneration for the time and research involved to provide quality links, we generally use affiliate links when we can. Whenever we link to something not our own, you should assume they are affiliate links or that we benefit in some way.

How Can We Help You? balloons
How Can We Help You?
bullet Custom Programming
bullet Ready-Made Software
bullet Technical Support
bullet Possibilities Newsletter
bullet Website "How-To" Info
bullet Useful Information List

© 1998-2001 William and Mari Bontrager
© 2001-2011 Bontrager Connection, LLC
© 2011-2024 Will Bontrager Software LLC