简体   繁体   中英

How can I make sure that a web-page opens up with scrollbar in the middle

I am trying to create a horizontally scrolling page and I want the page to open with scroll bar in the middle so that the user has option to scroll in both left and right directions(by default it opens with scrollbar at left). How can I do that?

Updated after comment If the body's width doesn't exceed the browser's viewport:
Scrolling inside an element :

var elem = document.getElementById("container"); //div#container
var elemWidth = elem.scrollWidth;
var elemVisibleWidth = elem.offsetWidth;
elem.scrollLeft = (elemWidth - elemVisibleWidth) / 2;


Use this code to vertically & horizontally center a page (see also: this answer ):

  window.scrollTo( (document.body.offsetWidth -window.innerWidth )/2, (document.body.offsetHeight-window.innerHeight)/2 ); 

To only center horizontally, use:

 window.scrollTo((document.body.offsetWidth -window.innerWidth )/2, 0); 

Use the JavaScript function scrollTo in the onload event. For more information on how to get the current window size, check out this article .

one possibility is to use javascripts scrollto when loading the page (simply put this in your onload or domready -event):

window.onload = function(){
  window.scrollTo(100, 100); // (X,Y)
}

just set the x/y values to the ones you need.

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