如何将元素锚定到窗口的左侧

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


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;在标题中进行设置,然后将awidth: 10000px;赋给main元素,则会看到我想要的布局。

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


茅侃侃
浏览 112回答 3
3回答

智慧大石

页脚是否需要进行硬编码width?这似乎是您遇到最多问题的地方。如果您仅在页脚中有需要显示的内容,并且内容可能比页眉宽,那么我建议您使用如下解决方案:html, body, main {&nbsp; width: 100%;&nbsp; height: 100%;&nbsp; background: #888;&nbsp; margin: 0;&nbsp; padding: 0;}header {&nbsp; width: 100%;&nbsp; height: 20%;&nbsp; background: rgba(0,255,0,.1);}footer {&nbsp; display: flex;&nbsp; overflow-x: scroll;&nbsp; height: 80%;&nbsp; background: rgba(255,0,0,.1);}h1 {margin-left: 70px;}<main>&nbsp; <header>Header</header>&nbsp; <footer>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; &nbsp; <h1>Content</h1>&nbsp; </footer></main>

江户川乱折腾

将标头CSS更改为此header {&nbsp; width: 100%;&nbsp; height: 20%;&nbsp; background: rgba(0,255,0,.1);&nbsp; position: fixed;&nbsp; float-left: auto;&nbsp; float-right: auto;}Fixed元素相对于html文档而不是父容器,并且不受滚动影响。Float left and right auto将其居中放置在页面上。如果要在垂直滚动footer上方进行浏览header,则应使用z-index属性。footer {&nbsp; width: 10000px;&nbsp; height: 80%;&nbsp; background: rgba(255,0,0,.1);&nbsp; position: fixed;&nbsp; z-index: 1}你也可以在绝对fixed和absolute相对于父容器之间进行比较fixed
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript