Prevent a centered layout from shifting its position when scrollbar appears

前端 未结 6 1315
灰色年华
灰色年华 2020-12-03 05:05

My page layout looks something like this:



6条回答
  •  不思量自难忘°
    2020-12-03 05:45

    First I would recommend optimizing the HTML so that it won't take so long to load/render. If load/render is fast the scrollbar won't appear "too late". What is it that takes long to load/render? Check the network tab in chrome debug tools (F12). Do an audit in Chrome debug tools.

    There are multiple things that could make the document "reflow", and the scrollbar appear even though the browser could have known the necessary measurements right from the start. Are you using tables for layout - don't! They may need multiple passes of rendering. Do you have images without width/height specified? Then the document will need to be rerendered when each image loads. Specify . Is the CSS sane and efficient?

    If you can't get load/rendering speed down I think your best bet is to not use the browser's scrollbar if javascript is enabled. That way you can control it and place it absolutely positioned so that it won't affect horizontal positioning.

    Let your slider start of with display: none. Monitor dom ready event as well as image load events as well as window resize events. When the page has been loaded, images have been loaded and when window gets resized just run the same function every time. It would determine if the scrollbar is needed and either display it or hide it.

    You could use JQuery UI Slider for example and set it's maxValue to $(document).height() - $(window).height(), monitor the slider change event and then scroll the body to the value of the slider and so forth.

    If javascript is disabled the fallback will be the regular scrollbar and there's nothing you can do about the slight horizontal shift then.

    But really I think the problem of the horizontal shift is too small to spend time fixing with a custom scrollbar, and check that it actually works well on all platforms etc. Do HTML/CSS optimizations first.

提交回复
热议问题