当内容(正文)溢出时,如何实现全宽度标题栏

3

HTML代码:

<body>
   <header style="background-color:green;">header</header>
   <main>
      <p>some content</p>
      <div style="width:2000px">some wide content, makes overflow body</div>
      <p>some content</p>
   </main>
   <footer>footer</footer>
</body>

当内容宽度大于窗口宽度时,会出现垂直滚动条 - 这正是我想要的。但是页眉和页脚的宽度为窗口宽度的100%。
我希望将页眉/页脚宽度扩展到内容宽度。 或者(更好的解决方案)页眉/页脚保持100%的宽度,我看到垂直滚动条(在窗口上),但是当我开始垂直滚动时,我只会滚动正文部分。页脚/页眉保持"粘性"。 我不能使用position:fixed,因为在水平滚动时,页眉/页脚应该随着内容"移动"。

1
我不太明白,一个使用fixed定位的元素在垂直或水平滚动时会随着内容移动。你可以在问题中附上代码片段来演示你的意思,这样能更清晰地传达信息。 - UncaughtTypeError
1个回答

4

body {
  /* Take width and height of content and use flexbox layout */
  /* By default all flex items will stretch for cross axis */
  display: inline-flex;
  /* Align all blocks in columns */
  /* All items will stretch in width */
  flex-direction: column;
  /* Minimum occupy 100% of screen width */
  min-width: 100vw;
  /* Minimum occupy 100% of screen height */
  /* To get rid of horizontal scrollbar can be changed to smaller value */
  /* e.g. min-height: calc(100vh - 20px) */
  /* Replace min-height with height to also work in IE */
  min-height: 100vh;
  margin: 0;
}

.content {
 /* Emulating long content */
  width: 9999px;
  /* Take all height */
  flex: 1 0 auto;
}

/* Styles just for demo */
header {
  background-color: yellow;
}

.content {
  background-color: orange;
}

footer {
  background-color: lime;
}
<header>Header</header>
<div class="content">Very long content</div>
<footer>Footer</footer>

如果您需要仅在水平方向上固定页眉和页脚,可以通过JavaScript实现此目的:

var header = document.querySelector("header");
var footer = document.querySelector("footer");

window.addEventListener("scroll", function(e) {
  var rect = document.body.getBoundingClientRect();
  header.style.marginLeft = -rect.left + "px";
  footer.style.marginLeft = -rect.left + "px";
});
body {
  /* Take width and height of content and use flexbox layout */
  /* By default all flex items will stretch for cross axis */
  display: inline-flex;
  /* Align all blocks in columns */
  /* All items will stretch in width */
  flex-direction: column;
  /* Minimum occupy 100% of screen width */
  min-width: 100vw;
  /* Minimum occupy 100% of screen height */
  /* To get rid of horizontal scrollbar can be changed to smaller value */
  /* e.g. min-height: calc(100vh - 20px) */
  /* Replace min-height with height to also work in IE */
  min-height: 100vh;
  margin: 0;
}

.content {
  /* Emulating long content */
  width: 9999px;
  height: 1000px;
  /* Take all height */
  flex: 1 0 auto;
}


/* Styles just for demo */

header {
  background-color: yellow;
}

.content {
  background-color: orange;
}

footer {
  background-color: lime;
}
<header>Header</header>
<div class="content">Very long content</div>
<footer>Footer</footer>


你有没有想法如何在垂直滚动时将页眉/页脚固定在左边缘? - massther
仅使用JavaScript。据我所知,水平和垂直滚动条应保留在窗口中。 - Vadim Ovchinnikov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接