我怎样才能把一个指定高度的头部固定在顶部,而不给兄弟部分添加顶部属性使其可见?

问题描述 投票:0回答:1

我有一个小问题,我正在做一个项目,在这个项目中,所有的东西都是分开的,我只做一个头部的部分,而不接触其他任何东西,我可以在所有的项目中只显示头部,这意味着什么?我没有权限触摸正文,只有heeader。

我必须将页眉设置为固定的,我之前已经这样做了,但它们是我的个人项目,我给页眉一个高度,然后将它旁边的部分相对定位,并为它添加top属性,这样页眉和部分就可以同时可见,页眉不必覆盖部分章节或部分内容。

让我们放一些代码。

<body>

    <header></header>
    <section class="first_section"></section>
    <section></section>

</body>

和这样的css。

header {  position :fixed; height: 40px; }
section { position : relative; }
.first_section { top: 40px }

现在,我不能这样做,我不能触摸部分或添加样式,为什么呢? 因为它们是非常动态的,头部可以包含在多个网站中,这意味着它是不合适的触摸所有部分或逐一覆盖它们。

因此,为了解决这个问题,我在html中试了一下。

<body>

    <header>
       <div class="header"></div>
    </header>
    <section class="first_section"></section>
    <section></section>

</body>

现在,我已经将所有的css属性从header传递到了带有header类名的div中,现在header是这样的。

header {  position :relative; width: 100%; height: 40px; }
.header { position: fixed; // many others properties }
section { position : relative; }
.first_section { top: 40px }

但它不工作,为什么?我不知道,但是当检查header的height属性时,它没有被设置,header在css文件中有width和height属性,但是当我检查时,我看到height是0,我想是因为它有一个固定的子代,但我不知道如何解决它。

任何帮助将是非常感激的。

html css css-position positioning
1个回答
1
投票

一个解决方案可能是创建2个divs在你的头:一个固定的真正的头,和另一个只是为了保持空间,所以没有什么将被覆盖。

<header>
  <div class="header trueHeader"></div>
  <div class="header"></div>
</header>

.header {
  height: 50px;
  width: 100vw;
}

.trueHeader {
  position: fixed;
  background-color: #f00;
}

例子。https:/jsfiddle.netjhsLngr41


0
投票

我知道答案已经被选中了,但一个简单的解决方案是使用position:sticky这样的......

body {
  margin: 0;
  padding: 0;
}
header {
  position: sticky;
  top: 0;
  height: 50px;
  background-color: red;
}
section {
  height: 750px;
  background-color: white;
}
footer {
  height: 50px;
  background-color: green;
}
.someClass {
  padding: 10px;
  margin: 0;
}
<header></header>
<section>
 <p class="someClass">
  scroll down..
 </p>
</section>
<footer></footer>
© www.soinside.com 2019 - 2024. All rights reserved.