Search code examples
javascriptscroll

Auto center horizontal scrollbar


I've found some related cases but no answer works for me. My page have a big horizontal image but I need to start scrolling it from the middle (just horizontally), always and in any resolution.

var body = document.body; // For Safari
var html = document.documentElement; // Chrome, Firefox, IE and Opera 
body.scrollLeft = (html.clientWidth - body.scrollWidth) / 2
html.scrollLeft = (html.clientWidth - body.scrollWidth) / 2
body {
  background-color: 0178fa;
  padding: 0;
  text-align: center;
  display: flex;
  justify-content: center;
  align-items: center;
  overflow: auto;
}

#page {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  padding: 0;
  display: block;
}

#wrap-landing {
  position: relative;
  margin: 0 auto;
  padding: 0;
  content: url(https://i.imgur.com/gb6EyHk.png);
  width: 1920px;
  height: 1080px;
}
<div id="page">
  <div id="wrap-landing"></div>
</div>


Solution

  • You could use standard javascript: window.scroll(x, y).

    Ex:

    window.addEventListener('load', function() {
      setTimeout(function() {
        window.scroll(x, y);
      },1)
    })
    

    x-coord is the pixel along the horizontal axis of the document that you want displayed in the upper left.

    y-coord is the pixel along the vertical axis of the document that you want displayed in the upper left.

    window.addEventListener('load', function() {
      setTimeout(function() {
        window.scroll(screen.width/2, 0);
      },1)
    })
    body{
        background-color:0178fa;
      padding:0;
      text-align:center;
        display: flex;
      justify-content: center;
      align-items: center;
        overflow:auto;
    }
    
    #page {
        width:100%;
        height:100%;
        margin:0 auto;
      padding:0;
        display:block;
    }
    
    
    #wrap-landing{
        position:relative;
        margin:0 auto;
      padding:0;
        content:url(https://i.imgur.com/gb6EyHk.png);
        width:1920px;
        height:1080px;
    
    }
    <!DOCTYPE html>
    <html>
    <head>
      <title></title>
    </head>
    <body>
      <div id="page">
        <div id="wrap-landing">
        </div>
      </div>
    </body>
    </html>