简体   繁体   中英

Center the background position of body / div to middle of Viewport

I have a Body height of 1000px, and my screen height is 100px. I wanted to display a <div> that occupies the entire <body> width and <body> height. That <div> is having one background-image and I want to make it displayed at the middle of the viewport. How can I achieve this using Javascript.

I have used the below concept but it did not work for me in mobile devices

  ele.style.backgroundPosition = document.body.scrollTop + 
                                 (window.innerHeight / 2) - heightOfImage;

The simplest solution may be to have a fixed positioned <div /> with the background image set on it, and it's z-index set such that it appears under all the other elements on the page.

Example: http://jsfiddle.net/gztRa/

If you really do want to go the JavaScript route (which I personally wouldn't do if I could help it here), you're going to have to do something along these lines:

  1. Hook up to the scroll event of the element thats scrolling
  2. Every time this fires, adjust the scroll position like so:

var verticalPosition = document.body.scrollTop + (window.innerHeight / 2) - heightOfImage;

ele.style.backgroundPosition = 'center ' + verticalPosition + 'px';

Note the addition of the 'px' as this is important. There is also a space after "center", so you should end up with something that looks like this: ele.style.backgroundPosition = 'center 50px' .

Example (using Zepto or jQuery): http://jsfiddle.net/7aqgG/7/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM