+-
导航条贴顶,主体为100%。

我正在构建一个react应用,有一个bootstrap的nabavr,是粘顶的。我已经将主体设置为 height: 100% 当我这样做的时候,导航条不再粘住。我不能在我的一个页面中使用vh,因为它会在移动设备上扰乱内容,所以我想坚持使用百分比。有什么方法可以做到这一点吗?我已经包含了使主体100%的代码。

html,
body,
#root {
  height: 100%;
  max-height: 100%;
}
-1
投票

你可以使用位置CSS属性(https:/developer.mozilla.orgen-USdocsWebCSSposition。).

如果有必要,你也可以使用z-index属性(https:/developer.mozilla.orgen-USdocsWebCSSz-index。)

例子:

HTML

<div id="root">
  <nav>
    <div>item</div>
    <div>item</div>
    <!-- ... -->
    <div>item</div>
    <div>item</div>
  </nav>
  <main>
    <!-- ... -->
  </main>
</div>

CSS

#root {
    /* necessary */
    position: relative;
    height: 100vh;
}

nav {
    /* necessary */
    position: sticky; // you can also use 'fixed' value
    top: 0;
    left: 0;
    right: 0;

    /* not necessary */
    background-color: red;
    height: 2rem;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
}

main {
  /* necessary */
  overflow: hidden auto;
  /* margin-top: 2rem; if you have used fixed value */

  /* not necessary */
  height: 200%;
  background-color: green;
}