32. sticky

fe.syhan·2023년 10월 31일

JS 기초

목록 보기
29/52
post-thumbnail

position : sticky


스크롤이 되어서 요소가 화면에 나오면 고정시킨다는 특성이 있다.

<body style="background : grey; height : 3000px">

<div class="grey">
  <div class="image">
    <img src="appletv.jpg" width="100%">
  </div>

  <div style="clear : both"></div>
  <div class="text">Meet the first Triple Camera System</div>
    
</div>

</body>
.grey {
  background: lightgrey;
  height: 2000px;
  margin-top: 500px;
}
.text {
  float: left;
  width : 300px;
}
.image {
  float: right;
  width : 400px;
  position: sticky;
  top: 100px;
}

스크롤이 되어서 이미지가 보이는 순간 viewport의 맨 위에서부터 100px 위치에서 고정이 된다. 그리고 부모 박스를 넘어서 스크롤이 되면 이미지도 같이 사라진다.

주의점

  1. 스크롤을 할 만한 부모 박스가 있어야 한다.
  2. top 등 좌표속성과 함께 써야 된다.

0개의 댓글