首页 > 解决方案 > HTML 滚动布局

问题描述

我正在尝试设计一个带有固定页眉和页脚以及可滚动中间的 HTML 屏幕布局。我正在尝试使用overflow:hiddenoverflow:auto在 CSS 中为布局的中央、可滚动部分获取滚动条,但没有成功。代码如下:

html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
  margin-block-start: 0;
  margin-block-end: 0;
  background-clip: padding-box;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  text-rendering: optimizeLegibility;
  box-sizing: border-box;
}

article {
  overflow-y: auto;
}

#site {
  width: 100%;
  height: 100%;
  margin: 0;
  overflow-y: hidden;
}

#hdr {
  font-weight: bold;
  text-align: center;
  padding-bottom: 1rem;
  padding-top: .5rem;
  color: violet;
}

#Document {
  height: auto;
  color: rgb(0, 0, 26);
  margin: 0;
  top: auto;
}
<div id="site">
  <!-- The entire document will initially be invisible
  and will be enabled for display through JavaScript -->
  <header id="hdr">
    Header should be fixed and contains the document title, 
    placed here with Javascript
  </header>
  <article id="Document" style="margin-top:1rem">
    <br><br>
    <br><br><br><br><br><br><br><br><br> 
    Article should scroll when needed. 
    Scroll down manually to see more content.
    <br><br>
    <br><br><br><br><br><br><br><br><br> 
    More text is displayed here
  </article>
  <footer style="margin-top:1rem">
    Footer should be fixed and will contain 
    copyright/publishing information
  </footer>
</div>

谁能看到我做错了什么并就如何使其发挥作用提出建议?我在 Ubuntu 20.04 上运行的 Chrome、Firefox 和 Opera 上尝试了此代码,但没有任何成功。

标签: htmlcss

解决方案


它可以通过 flexbox 布局来完成。

html,
body {
  height: 100%;
  width: 100%;
  margin: 0;
}

* {
  text-rendering: optimizeLegibility;
  box-sizing: border-box;
}

#site {
  margin: 0;
  height: 100%;
  display: flex;
  flex-direction: column;
}

#header {
  font-weight: bold;
  text-align: center;
  padding-bottom: 1rem;
  padding-top: .5rem;
  color: violet;
}

#Document {
  flex: 1;
  overflow: auto;
  background: lightblue;
}

#footer {
  font-weight: bold;
  text-align: center;
  padding-bottom: 1rem;
  padding-top: .5rem;
  color: violet;
}
<div id="site">
  <!-- The entire document will initially be invisible
  and will be enabled for display through JavaScript -->
  <header id="header">
    Header should be fixed and contains the document title, 
    placed here with Javascript
  </header>
  <article id="Document">
    <br><br>
    <br><br><br><br><br><br><br><br><br> 
    Article should scroll when needed. 
    Scroll down manually to see more content.
    <br><br>
    <br><br><br><br><br><br><br><br><br> 
    More text is displayed here
  </article>
  <footer id="footer">
    Footer should be fixed and will contain 
    copyright/publishing information
  </footer>
</div>


推荐阅读