【问题标题】:Make a fixed HTML <nav>制作固定的 HTML <nav>
【发布时间】:2021-04-04 09:09:36
【问题描述】:

我使用position: fixed 样式使&lt;nav&gt; 不动。但是,如果有&lt;header&gt;,则有与&lt;header&gt; 区域一样多的边距。向上移动到&lt;header&gt; 区域后,我想将其固定在该位置。

我正在使用 React 库,我正在自学,所以很难找到方法。

#hd a {
  font-family: "array";
  font-size: 30px;
}

#hd {
  margin-left: 0.5%;
  width: 99%;
  height: 45px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  text-align: center;
}

#btn1 {
  width: 100px;
  height: 30px;
  border-radius: 30px;
  background-color: white;
  border-color: #71bbff;
  outline: 0;
}

#btn2 {
  width: 100px;
  height: 30px;
  border-radius: 30px;
  background-color: #71bbff;
  outline: 0;
  border-color: #71bbff;
  margin-left: 25px;
}
/* header */

/* main */
#main {
  width: 100%;
  height: 600px;
}

nav a {
  text-decoration: none;
  color: white;
  font-size: 25px;
}

nav {
  width: 100%;
  height: 60px;
  position: absolute;
}

nav:hover {
  background-color: black;
}

/*
#nav.sticky {
  position: fixed;
  margin-top: -45px;
  background: white;
  box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);
}
*/

ul {
  height: 60px;
  display: flex;
  justify-content: space-around;
  align-items: center;
  list-style: none;
}

ul li {
  width: 130px;
  text-align: center;
}

ul li:hover {
  transition:all .3s ease-out;
  border-bottom: 1px solid orange;
}

#fmenu ul {
  position: absolute;
}

#smenu {
  border-top: 1px solid orange;
  width: 130px;
  height: 240px;
  display: none;
  background: black;
}

#smenu li {
  margin-top: 13px;
  width: 100%;
}

#smenu li:hover {
  background-color: peru;
}

#fmenu:hover #smenu {
  display: block;
}
<header id="hd">
  <img src="http://picsum.photos/45/45.jpg" width='45' />
  <a>Array</a>
  <div id="btn">
    <button id="btn1"href="#">Login</button>
    <button id="btn2"href="#">회원가입</button>
  </div>
</header>
<div id="main">
  <nav id="nav">
    <ul>
      <li><a href="#">Array</a></li>
      <li id="fmenu"><a href="#">커뮤니티</a>
        <ul id="smenu">
            <li><a href="#">자유게시판</a></li>
            <li><a href="#">질문게시판</a></li>
            <li><a href="#">정보게시판</a></li>
            <li><a href="#">프로젝트</a></li>
            <li><a href="#">일기장</a></li>
          </ul></li>
      <li><a href="#teamw">구성원</a></li>
      <li><a href="#union">연합팀</a></li>
    </ul>
  </nav>
</div>

【问题讨论】:

    标签: html css navigation css-position


    【解决方案1】:

    您需要将导航标签在 DOM 树中向上移动一级,而不是使用固定位置来使元素的位置保持不变,而是使用相对定位的粘性位置,直到它超过指定的阈值,此时它是视为固定定位。这是相关部分:

    <header>....</header>
    <nav id='nav'>...</nav>
    <div id='main>...</div>
    

    在css中,

    nav{
      width: 100%;
      position: sticky;
      top:0;
      background-color: #000;
    }
    

    进行这些更改以获得您想要的效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-08-12
      • 1970-01-01
      • 2010-09-30
      • 2011-01-10
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      相关资源
      最近更新 更多