스크롤을 내리면 해더가 같이따라 올라가다가 특정 높이가되면 올라갔던 해더가 주르륵 내려오는 효과를 적용해보자
구글,네이버등등에 적용된 효과
먼저 html 구조를 짜고
<body>
<div class="header">
<ul>
<li><a href="">menu1</a></li>
<li><a href="">menu2</a></li>
<li><a href="">menu3</a></li>
</ul>
</div>
<div class="main">
<div class="section">
the header gets dropped and fixed on scroll down!
</div>
<div class="section">
the header gets position back on scroll up
</div>
</div>
</body>
다음은 css
@import url('https://fonts.googleapis.com/css2?family=Roboto&display=swap');
* {
margin: 0;
padding: 0;
}
body {
width: 100%;
background: #333;
color:#ccc;
font-family: 'Roboto', sans-serif;
}
ul {
list-style: none;
}
a {
display:inline-block;
text-transform: uppercase;
text-decoration: none;
color: #333;
padding: 0 40px;
line-height:5rem;
height:5rem;
}
a:hover{
background:#444;
color:#ccc;
}
.header {
width: 100%;
height: 5rem;
background: #eee;
position: absolute;
top: 0;
left: 0;
}
.header ul {
width: 100%;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.section {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 5rem;
box-sizing: border-box;
text-align: center;
}
.section:nth-child(even) {
background: #ccc;
color:#333;
}
스크롤y값이 헤더높이를 벗어나면 header에 class 'drop'을 붙여줌으로써 header를 고정시키고
애니메이션을 넣어줄 예정이므로 css에 class "drop"인 경우에 적용될 css를 정의해준다.
.header.drop {
position: fixed;
animation: dropHeader 0.3s;
}
@keyframes dropHeader {
0% {
top: -5rem;
}
100% {
top: 0;
}
}
마지막으로 기능구현을 위해 스크립트 작성
자바스크립트랑 친해지기 위해서 쌩자바스크립트로 작성했습니다.
let header = document.querySelector(".header");
let headerHeight = header.offsetHeight;
window.onscroll = function () {
let windowTop = window.scrollY;
// 스크롤 세로값이 헤더높이보다 크거나 같으면
// 헤더에 클래스 'drop'을 추가한다
if (windowTop >= headerHeight) {
header.classList.add("drop");
}
// 아니면 클래스 'drop'을 제거
else {
header.classList.remove("drop");
}
};
완성된 예제를 보자
See the Pen by Euiyeon (@rhdmldus) on CodePen.
반응형
'퍼블리싱' 카테고리의 다른 글
[CSS] 프로그레스바 circular progess bar 만들기 (0) | 2021.08.20 |
---|---|
[CSS] 다크모드 적용하기 (dark mode) width pure css (0) | 2021.08.19 |