我的页面包含两个元素:页眉和页脚。
html,
body,
main {
width: 100%;
height: 100%;
background: #888;
margin: 0;
padding: 0;
}
header {
width: 100%;
height: 20%;
background: rgba(0, 255, 0, .1);
}
footer {
width: 10000px;
height: 80%;
background: rgba(255, 0, 0, .1);
}
<main>
<header></header>
<footer></footer>
</main>
请检查此codepen举个例子。
当我水平滚动窗口时,我需要标题始终位于屏幕中间居中。
我无法使用 position:fixed
因为我需要此元素位于页面流中。
position: Sticky
正是我所需要的,但不幸的是我无法使用它,因为父元素的宽度与视口(viewport)宽度相同。如果我将父宽度设置为大于视口(viewport)本身的宽度,我就达到了我想要的效果,但我希望有更好的解决方案。
我更喜欢纯 CSS 解决方案,但我对 JS 解决方案持开放态度。
到目前为止,我尝试过的许多事情之一是监听滚动事件,并向元素添加等于 window.scrollX
的左边距,其想法是它将保持锚定到窗口的左边缘。但这实际上不起作用,我不知道为什么。
在示例中,如果您尝试设置 position: Sticky; left: 0;
在标题中,然后给主元素一个 width: 10000px;
,你会看到我想要的布局。
是否可以实现相同的布局,但无需设置宽度?
最佳答案
页脚是否需要有硬编码的宽度
?这似乎是您遇到最多问题的地方。如果您只是需要在页脚中显示内容并且可能比页眉更宽,那么我建议使用如下解决方案:
html, body, main {
width: 100%;
height: 100%;
background: #888;
margin: 0;
padding: 0;
}
header {
width: 100%;
height: 20%;
background: rgba(0,255,0,.1);
}
footer {
display: flex;
overflow-x: scroll;
height: 80%;
background: rgba(255,0,0,.1);
}
h1 {
margin-left: 70px;
}
<main>
<header>Header</header>
<footer>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
<h1>Content</h1>
</footer>
</main>
关于javascript - 如何将元素锚定到窗口的左侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56080633/