首页 > 解决方案 > 如何将元素锚定到窗口的左侧

问题描述

我有一个包含两个元素的页面,一个页眉和一个页脚。

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;主元素一个,您将看到我想要的布局。

是否可以实现相同的布局,但不必设置宽度?

标签: javascripthtmlcss

解决方案


页脚是否需要硬编码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>



推荐阅读