javascript - 如何将元素锚定到窗口的左侧
问题描述
我有一个包含两个元素的页面,一个页眉和一个页脚。
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>
请检查此代码笔以获取实时示例。
当我水平滚动窗口时,我需要标题始终位于屏幕中间。
我不能使用position: fixed
,因为我需要这个元素在页面流中。
position: sticky
完全符合我的需要,但不幸的是我不能使用它,因为父元素的宽度与视口宽度相同。如果我将父宽度设置为大于视口本身的宽度,我会实现我想要的,但我希望有一个更好的解决方案。
我更喜欢纯 CSS 解决方案,但我对 JS 解决方案持开放态度。
到目前为止,我尝试过的许多事情之一是侦听滚动事件并向等于 的元素添加一个边距window.scrollX
,其想法是它将保持锚定在窗口的左边缘。但是这实际上不起作用,我不确定为什么。
在示例中,如果您尝试position: sticky; left: 0;
在标题中设置,然后给width: 10000px;
主元素一个,您将看到我想要的布局。
是否可以实现相同的布局,但不必设置宽度?
解决方案
页脚是否需要硬编码width
?这似乎是您遇到最多问题的地方。如果您只是在页脚中有需要显示的内容并且可能比页眉更宽,那么我建议使用如下解决方案:
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>
推荐阅读
- c++ - 使用 PortAudio 和 libaudiodecoder 的 3D 音频
- c - 如何通过多字节数组移动一个字节
- c++ - wxColour 用 int 数组设置?
- git - Git对已标记为已合并的文件进行三向合并
- javascript - PHP:将javascript对象字符串转换为php数组
- mysql - Heroku 上的 Rails 布尔值不会从 0 切换到 1
- linux - 制作一个 bash 脚本来刷新值,而无需像 TOP 命令那样向下滚动终端
- php - Docker 从 git 下载代码并运行 php 内部服务器
- dart - 如何在 Hot Reload 上使用 Provider 维护 Flutter Global BloC 状态?
- python - 如何在if语句中调用函数并保存返回值