본문 바로가기
HTML&CSS

[CSS] 배경 고정한 채로 스크롤 움직이기

by dev또리 2023. 12. 5.
728x90

 

 

background-attachment ?

- background-attachment 가 배경 이미지 스크롤 시에도 고정시키는 효과

- scroll(기본값) : 배경이미지가 스크롤 시 페이지와 함께 스크롤 처리

- fixed : 배경이미지가 스크롤 시 페이지와는 다르게 고정처리

 

background-attachment: fixed;

 

 

 

 

HTML

<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="UTF-8">
        <title>배경 고정하기</title>
        <style> /* 스타일 */ </style>
    </head>
    <body>
        <header></header>
        <main></main>
        <div class="contents01"></div>
        <div class="fixed01"></div>
        <div class="contents02"></div>
        <div class="fixed02"></div>
        <div class="contents03"></div>
        <footer></footer>
    </body>
</html>
 

 fixed01,fixed02 div태그에 배경이미지 고정하기 !

 

 

CSS

*{ padding: 0; margin: 0; }
            
header{ width: 100%; height: 100px; background-color: pink; }
footer{ width: 100%; height: 100px; background-color: #333; }
main{ width: 100%; height: 600px; background-color: beige; }
.contents01, .contents02, .contents03{ width: 100%; height: 400px; background-color: orange; }

.fixed01{
  width: 100%; height: 300px;

  /* 배경이미지는 최소 1920*960으로 제작해야 문제 없음 */
  background-image: url(img01.jpg);
  background-repeat: no-repeat; /* 배경이미지X */
  background-size: cover; /* 요소를 비율에 맞게 커버 */
  background-position: center; /* 이미지를 요소의 정가운데로 처리 */
  background-attachment: fixed; /* 스크롤바 움직일때 이미지가 따라다님 */
}

.fixed02{
  width: 100%; height: 300px;

  /* 배경이미지는 최소 1920*960으로 제작해야 문제 없음 */
  background-image: url(img02.jpg);
  background-repeat: no-repeat; /* 배경이미지X */
  background-size: cover; /* 요소를 비율에 맞게 커버 */
  background-position: center; /* 이미지를 요소의 정가운데로 처리 */
  background-attachment: fixed; /* 스크롤바 움직일때 이미지가 따라다님 */
}

 

- 높이를 960인 이유: 브라우저 상단을 빼고 운영체제의 작업표시줄을 뺀 높이

- 배경이미지를 처리후 해상도가 1920보다 커도 잘리는 이미지 없게 background-size: cover;

 

728x90

댓글