简体   繁体   中英

Make a fixed HTML <nav>

I used the position: fixed style to make the <nav> not moving. However, if there is a <header> , there is a margin as much as the <header> area. After moving upward as much as the <header> area, I want to fix it at that position.

I'm using the React library, I'm studying on my own so it's hard to find a way.

 #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>

You need to move your nav tag one level up in the DOM tree and instead of fixed position which makes the position of the element constant, use sticky position which is relative positioned until it crosses a specified threshold, at which point it is treated as fixed positioned. Here is relevant part:

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

In the css,

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

Make these changes to get your desired effect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM