出现滚动条时,防止居中布局移位 [英] Prevent a centered layout from shifting its position when scrollbar appears

查看:137
本文介绍了出现滚动条时,防止居中布局移位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的页面布局看起来像这样

My page layout looks something like this:

<style type="text/css">
#content-wrap
{
    margin: 0 auto;
    width: 800px;
}
</style>

<div id="content-wrap">
</div>

您会注意到当垂直滚动条出现时,content-wrap div稍微改变了它的位置。一种情况是,浏览器开始逐渐渲染页面而不显示垂直滚动条,然后确定需要滚动条,因为内容比折叠更高。这使得div向左移动了大约10px。

You'll notice that the content-wrap div shifts its position a tad bit when the vertical scrollbar appears. One scenario is when the browser starts to progressively render the page without displaying the vertical scrollbar, then determines that a scrollbar is needed because the content is taller than the "fold". This shifts the div about 10px towards left.

在不强制浏览器始终显示滚动条的情况下,解决此问题的最佳方法

What is the best way to tackle this problem without forcing the browser to always display the scrollbar?

推荐答案

恐怕解决这个问题的最好方法是强制滚动条在任何时候都可见 html {overflow-y:scroll;} 。你遇到的问题是,当滚动条出现时,可用区域缩小为10px。这会导致左侧的计算边距缩小为滚动条宽度的一半,从而将居中内容稍微向左移动。

I'm afraid the best way to solve this is to force the scroll bar to be visible at all times with html {overflow-y: scroll;}. The problem you have is that the "available area" shrinks with say 10 px when the scroll bar appear. This cause the calculated margin on your left side to shrink with half the width of the scroll bar, thus shifting the centered content somewhat to the left.

一个可能的解决方案可能是使用JavaScript计算保证金,而不是使用 margin:0 auto; 并以某种方式补偿对于出现滚动条时的丢失像素,但恐怕会很乱,并且在计算和应用新边距时,内容可能会稍微移动一些。

A possible solution might be to calculate the margin with JavaScript instead of using margin: 0 auto; and somehow compensate for the "lost" pixels when the scroll bar appear, but I'm afraid it will be messy and the content will probably move a little bit anyway while you calculate and apply the new margin.

这篇关于出现滚动条时,防止居中布局移位的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆