设置滚动条的位置



在我的网站上,我有两个主要divs- 一个用于顶部的横幅,一个用于主要内容。它们都包含内部元素,如imgsiframes等,但我认为这对我的问题并不重要,即:如何使主要内容的滚动条不与横幅重叠?

如果有帮助,您可以在我的github上查看我的实际网站的源代码。但是为了节省浪费时间,我在html中写了一个小片段来演示这个问题:

document.getElementById("someText").innerText = "this is some content ".replace(/ /g, 'n').repeat(15);
html, body {
margin: 0;
padding: 0;
}
#header {
position: fixed;
background-color: teal;
z-index: 1;
top: 0;
height: 100px;
width: 100%;
}
#main {
postion: absolute;
top: 100px;
}
<body>
<div id="header">
header
</div>
<div id="main">
<pre id="someText"></pre>
</div>
</body>

可能很难看到,在SO的片段中,但右侧的scroll bar与横幅重叠,我想要的是让它在到达横幅时停止。

我已经尝试(在CSS中(将身体的overflow设置为hidden,因为这是与横幅重叠scroll bar,但这只是完全删除了它,所以我无法滚动 - 所以显然不是我想要的......

我还尝试将maindivoverflow-y设置为scroll,但这不起作用,因为bar确实出现在我想要的地方,但它grayed-out无法使用。

我为您创建了一个小提琴: https://jsfiddle.net/3gvowvag/1/

你的HTML和JS保持不变。对于您的 CSS:

html, body {
margin: 0;
padding: 0;
overflow-y: hidden;
}
#header {
position: fixed;
background-color: teal;
z-index: 1;
top: 0;
height: 100px;
width: 100%;
}
#main {
position: absolute;
top: 100px;
max-height: 100%;
width: 100%
overflow-y: scroll;
}

所以这些变化基本上是给你的html, body一个overflow-y: hidden,你的#main一个max-heightwidth100%overflow-y: scroll

这基本上可以满足您的需求 - 尽管我对设置这样的页面没有 100% 的信心。通过像素进行绝对定位和偏移有点老派,还将 html/body 的溢出 y 设置为隐藏,不确定这些东西从长远来看会如何表现。但是,如果没有进一步的背景,很难完全想到这一点。

附言:真棒猫!

您只需要将overflow-y: hidden;添加到正文中(看看前面的答案(,然后将overflow-y: scroll;应用于#maindiv。

document.getElementById("someText").innerText = "this is some content ".replace(/ /g, 'n').repeat(30);
html, body {
margin: 0;
padding: 0;
}
body {
overflow-y: hidden;
}
#header {
position: fixed;
background-color: teal;
z-index: 1;
top: 0;
height: 100px;
width: 100%;
}
#main {
postion: absolute;
top: 100px;
overflow-y: scroll;
}
<body>
<div id="header">
header
</div>
<div id="main">
<pre id="someText"></pre>
</div>
</body>

您可能会发现使用弹性框布局更容易。也许是这样的。例如,如果您不想看到灰色的滚动条,请将溢出设置为自动

<div class="wrapper">
<div class="header">
header
</div>
<div class="content">
content
content
content
</div>
</div>
.wrapper{
display:flex;
flex-direction:column;
background:blue;
height: 100vw;
}
.header{
height:100px;
background-color:pink
}
.content{
background:green;
flex-grow: 1;
overflow:scroll;
}

最新更新