navigation fixed 하기

채연·2023년 3월 27일
0

목록 보기
9/22

fixed

fixed는 스크롤을 계속 내려도 고정이 되게끔 만들어주는 요소이다.

하지만 이걸 적용시, 예상치 못한 문제가 발생하게 된다!

fixed를 적용하게 되면 그 요소가 위에 떠있는 방식으로 구현이 되는데, 그럼 그 다음 요소들이 그 밑으로 들어가서 겹쳐 안 보이게 된다.

<div>
      <div
        style={{
          position: "fixed",
          height: "100px",
          width: "100%",
          backgroundColor: "aqua",
        }}
      />
      <div style={{ height: "3000px", width: "100%" }}>asdfasdf</div>
    </div>

-> 위의 div태그는 네비게이션 바로, 스크롤이 계속되어도 위에 고정이 되어있게 할 것이다.
그리고, 그 아래에 asdfasdf라는 글이 적힌 div태그를 넣고 싶다.

3000px만큼 준 이유는 스크롤이 되게 하고 싶어서 넣어주었다.


코드를 실행시켜보면 100px height가 보이고, asdfasdf라는 글은 보이지 않는다.


왜 이렇게 됐을까?

아까 위에서 말했던 것과 같은 상황이다. 현재 asdfasdf라는 글은 aqua 배경 밑에 써져있다.
그럼 그만큼을 내려주면 되겠다!

aqua가 100px이니까, asdfasdf 글 써진 div를 100px만큼 밑으로 내려준다.

aqua 의 안 보이는 부분도 배경색을 칠하고 싶으면 padding, 칠하지 않아도 되면 margin을 주면 된다.

우린 페이지 전체 색을 gray로 바꿔보자.

전체 색을 바꾸고 싶은 경우는 padding으로 하는 것이 좋다!

<div>
  <div
    style={{
      position: "fixed",
      height: "100px",
      width: "100%",
      backgroundColor: "aqua",
    }}
  />
  <div style={{ height: "3000px", width: "100%", paddingTop: "100px" }}>
    asdfasdf
  </div>
</div>

-> 앞서 말했던 것과 같이 paddingTop: "100px"를 준 결과

글이 이제 보이는 것을 확인할 수 있다.


번외

sidenavigation이 있을 경우에도 같은 방식으로 사용하면 좋다.

  • sidenavigation이 header보다 위에 있어야 하는 경우
    - sidenavigation을 더 나중에 만들어준다.
    <div>

      {/* header */}
      <div
        style={{
          position: "fixed",
          height: "100px",
          width: "100%",
          backgroundColor: "aqua",
        }}
      />
      
      {/* sidenavigation */}
      <div
        style={{
          position: "fixed",
          width: "300px",
          backgroundColor: "yellow",
          height: "100%",
        }}
      />
      <div
        style={{
          height: "3000px",
          width: "100%",
          paddingTop: "100px",
          paddingLeft: "300px",
        }}
      >
        asdfasdf
      </div>
    </div>


  • sidenavigation이 header보다 아래에 있어야 하는 경우
    - header를 더 나중에 만들어준다.

        <div>
         {/* sidenavigation */}
         <div
           style={{
             position: "fixed",
             width: "300px",
             backgroundColor: "yellow",
             height: "100%",
           }}
         />
    
         {/* header */}
         <div
           style={{
             position: "fixed",
             height: "100px",
             width: "100%",
             backgroundColor: "aqua",
           }}
         />
    
         <div
           style={{
             height: "3000px",
             width: "100%",
             paddingTop: "100px",
             paddingLeft: "300px",
           }}
         >
           asdfasdf
         </div>
       </div>

profile
Hello Velog

0개의 댓글