1

我试图将 DIV 元素的内容居中,该元素的滚动条隐藏在父元素后面。看起来像这样:

http://jsfiddle.net/Zeyar/

HTML:

<div class="parent">
    <div class="child">
        <div class="content">
            This should be centered! This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!This should be centered!
        </div>
    </div>
</div>

CSS:

.parent {
  width: 300px; /* unknown width - 100%* - browser size */
  height: 200px; /* unknown width - 100%* - broser size */
  overflow: hidden;
  background: #dedede;
}
.child {
  width: 120%; 
  height: 100%;
  overflow-y: scroll;
  background: #000;
}
.content {
    width: 150px;
    margin: 0 auto;
    background: #fff;
}

我尝试了各种各样的东西,但似乎没有任何效果。

我希望跨浏览器完成此操作,如果用户重新调整窗口大小,它仍然可以工作。我的问题是不同浏览器中的滚动条宽度会发生变化,并且屏幕宽度也是未知的。

4

2 回答 2

0

这是一种适用于所有浏览器的方法。

修改你的CSS如下:

body, html {
    height: 100%;
    margin: 0;
    padding: 0;
}
.parent {
    height: 100%;    /* unknown width - 100%* - browser size */
    overflow: hidden;
    background: #dedede;
}
.child {
    width: 120%;
    height: 100%;
    overflow-y: scroll;
    background: #000;
    position: relative;
}
.content {
    background: #fff;
    width: 150px;
    position: absolute;
    left: 45%;
    margin-left: -75px;
}

设置position: relative.child块上,然后position: absolute.content块上使用。

要使居中起作用,请使用left: 45%,然后.content使用 向左移动margin-left: -75px

45% 的值是基于一些尝试和错误。

限制

如果您将窗口宽度缩小到足够小,您会发现 周围的左右间距.content不太对称(相差 2-3 个像素)。

如果窗口足够高,则内容不会到达屏幕底部,因此不会垂直居中。

浏览器支持和 Safari 怪癖 我在 Windows 中尝试了 Safari 的解决方案,但使用鼠标滚动时垂直滚动不起作用。但是,该解决方案适用于 FF、IE、Chrome、Opera(最新版本)。

演示小提琴:http: //jsfiddle.net/audetwebdesign/q3bKz/

于 2013-08-01T11:09:56.783 回答
0

在查看了您的 jsfiddle 之后,我发现了它没有居中的原因。您已将宽度设置为 120%,如果将其更改为 100%,它将以子 div 为中心。但是,在执行此操作时,它确实带回了滚动条。不过我正在努力。

更新

我知道你已经接受了一个答案,但如果你不想使用 javascript/jquery 而只是使用普通的 css,那么你也可以尝试在 css 中使用它

.content {
    width: 150px;
    margin: 0 auto;
    background: #fff;
    -webkit-transform: translate(-20%, -20%);
    -moz-transform: translate(-20%, -20%);
    -ms-transform: translate(-20%, -20%);
    transform: translate(-20%, -20%);
}
于 2013-08-01T10:44:13.623 回答