【问题标题】:Sticky header with %-height and 100% content sections带有 %-height 和 100% 内容部分的粘性标题
【发布时间】:2014-09-28 23:23:20
【问题描述】:

我想要一个带有 %-height 属性的粘性标题。页眉下方的部分应占据页面的剩余高度,例如:header=10% 所有其他部分至少占 90%。这类似于一个相关问题:CSS Sticky Header/Footer and Fully Stretched Middle Area?,但他使用的是固定的 px-height,而我想要 %-height。我试图在我的部分使用边距,但这似乎不起作用。在我的部分上使用边距和 90% 的高度似乎不起作用。

目前我能够想出:http://jsfiddle.net/K9m63/。但是有几个问题:

  1. 第一部分消失在标题下方。
  2. 由于第 1 点,部分 div 太高,因此没有占用剩余大小。

HTML

<header>
    <nav>Test</nav>
</header>
<section>
    <div class="container yellow">1</div>
</section>
<section>
    <div class="container pink">2</div>
</section>
<section>
    <div class="container purple">3</div>
</section>

CSS

body, html {
    height: 100%;
}
header {
    height: 10%;
    background-color: green;
    position: fixed;
    top: 0px;
    width: 100%;
}
.helper {
    display: inline-block;
    height: 100%;
    vertical-align: middle;
}
.nav-image {
    vertical-align: middle;
}
section {
    height: 100%;
    width: 100%;
    background-color: red;
}
.container {
    width: 72.8125%;
    background-color: blue;
    margin: 0px auto;
    height: 100%;
}
.yellow {
    background-color: yellow;
}
.pink {
    background-color: pink;
}
.purple {
    background-color: purple;
}

谢谢!

【问题讨论】:

  • 为什么使用position: fixed; top: 0px;?通过删除它,您可以看到第一个 div 的内容。
  • 因为它需要粘性并保持在相同的位置(= 顶部:0px 并固定)。
  • 然后您可以使用body{padding-top: 38px;} 以便显示内容。检查演示。 jsfiddle.net/K9m63/1
  • 我不想在标题section{other section}之间有任何空格。现在它们是那些不需要的项目之间的空间。在调整我的屏幕大小时,我使用固定填充得到了不想要的效果(它必须是响应式的;-))。

标签: html css


【解决方案1】:

可能的解决方案:

我已将所有部分包装成 2 个 div。

<div class="wrapper">//rest 90% of the page
    <div class="wrapper2">//100% of parent
        <section>
            <div class="container yellow">1</div>
        </section>
        <section>...
    </div>
</div>

CSS:

.wrapper {
    min-height:90%;
    height:auto !important;
    position:relative;
    top:10%;
}
.wrapper2 {
    height:100%;
    width:100%;
    position:absolute;
}

另外,将z-index:1; 添加到header

在此处更新fiddle

【讨论】:

  • 看起来正是我想要实现的目标,谢谢!
  • @Hiral 一个问题 tho.. 是否也可以让它的最小高度为 100%?所以只要内容太长而不能 100% 增长,它就会增长?
  • @Velth 100% 高度是什么?
  • @Hiral 至少为 100%(在 .wrapper2 类上),所以每当
    的内容增长超过 100%,但所有其他 wrapper2-classes 保持默认 100%(如果合适)。
  • @Velth 我不这么认为
【解决方案2】:

根据您的图纸,您可以*这样做。 - 但也有“固定”/或“粘性”定位。 - 这种布局会迫使你在下面实现自己的滚动 - 在页面内容中,这很痛苦。

html, body {
  height: 100vh; /* you can use vh or % - but either way... */
  height: 100%; /* they don't know their own height... how would they? */
}

body {
  margin: 0;
}

.site-header {
  background: #ff6666;
  height: 10%;
}

.page-content {
  background: #6666ff;
  height: 90%;
}
<header class="site-header">
  header
</header>

<main class="page-content">
  main
</main>

【讨论】:

    猜你喜欢
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 1970-01-01
    • 2015-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多