내가 몰랐던 HTML/CSS part 5. position:fixed 와 :sticky의 차이

Seri Park·2021년 3월 17일
5

의미가 비슷해보여 헷갈릴수있지만
sticky와 fixed가 동작하는 차이는 뚜렷하다.

fixed는 viewport에 고정 되어 있는 것이고 스크롤을 내려도 원하는 위치에 고정되어있다. 그에 반해 sticky는 스크롤을 따라 움직이다 내가 정한 offset에 닿으면 그 순간부터 fixed처럼 고정이 된다. 최초에 relative 속성처럼 동작하다가 스크롤이 특정 지점에 도달하면 fixed 속성으로 동작하는 것이다.

sticky의 특징:

1. top, right, bottom, left 속성이 필수.
fixed 박스는 뷰포트에 고정하지만 sticky 박스는 scroll 박스에 고정한다. 즉, scroll 박스가 offset 기준.
(뷰포트와 scroll 박스가 동일한 것처럼 보이는 경우도 있겠지만 뷰포트는 하나뿐이고 scroll 박스는 문서 안에서 더 생성 가능.)

2. sticky 박스를 scroll 박스에 고정하는 임계점은 스크롤 위치가 결정함. sticky 박스 자신과 부모의 위치와 크기도 임계점에 영향을 미침.

3. sticky 박스의 부모 박스가 scroll 박스를 벗어나면 sticky 박스는 다시 일반적인 흐름을 따름.

4. sticky 박스와 scroll 박스 사이에 overflow: hidden 속성을 적용한 박스가 끼어들면 sticky 박스는 일반적인 흐름을 따름.

When to use fixed : 언제 fixed를 써야할까

So with that in mind, we want to use fixed
when it must always be on the same place on the page at all times. It simply doesn’t move.
Be careful with fixed though. Using it takes that element out of the document flow.
Visitors to your page can see it, but as far as the rest of the content on the page is concerned, it isn’t there.
That means it can potentially cover some elements, hiding them from view. Sometimes it’s not a big deal on desktop, but when you hit mobile and screen real-estate is limited, this can cause problems.

When to use sticky : 언제 sticky를 써야할까

You’ll want to use sticky
when you specifically have something that you want to scroll into view and then stop once it reaches a certain point.
In the past we had to use JavaScript to do this. It’s amazing that we can do it with CSS now, and that it’s so simple to use.
Keep in mind that it stays within its parent, so once the parent scrolls off, it’s gone. This isn’t an issue if the parent is the body, but the rest of the time you might not get the effect you are after.

profile
front-end developer. key= "consistency"

0개의 댓글