반응형
웹 페이지 미니 프로젝트(Web Page Mini Project)
Web Page Components
헤더 기본헤더 푸터 사이드 바 배너 폼 카드 모달
idocleancode.tistory.com
고정 헤더
- 고정 헤더는 웹페이지에서 스크롤을 해도 항상 화면 상단에 위치한 상태로 유지되는 헤더를 말합니다.
- 주로 웹사이트의 메인 메뉴나 로고, 검색창 등 주요 기능을 담고 있어, 사용자가 편리성을 제공합니다.
고정 헤더 원리
CSS
- position : fixed
고정 헤더는 CSS의 position 속성을 활용해 만들어집니다. 이 속성은 요소의 위치를 결정하는 데 사용되며, 그중 fixed 값이 고정 헤더를 만드는 데 주로 사용됩니다. - top:0
top 속성은 요소의 수직 위치를 설정하는데 사용됩니다. 여기서 0이면 최상단에 배치가 됩니다.
header {
position: fixed;
top: 0;
}
하면서 깨달은점
position: fixed를 사용하면 중앙 배치 margin: 0 auto가 작동이 안 되는 이유
- "position:fixed"는 문서 흐름을 무시하고 뷰포트에 고정된 위치에 요소를 배치하지만, "margin: 0 auto"는 일반적인 문서 흐름에서 자동하며 부모 요소의 가로 중앙에 위치하도록 하는데, 이 두 속성은 함께 사용이 어럽다
- 고정 위치에 요소를 가운데 위치하고 싶으면 "left와 transform" 속성을 사용해 배치할 수 있습니다.
header {
position: fixed;
left: 50%;
transform: translateX(-50%);
}
배포
HTML
더보기
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>고정 헤더</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header>
<div class="logo">
<h1>Logo</h1>
</div>
<nav>
<ul>
<li><a href="#">네비1</a></li>
<li><a href="#">네비2</a></li>
<li><a href="#">네비3</a></li>
</ul>
</nav>
</header>
<section id="section1">
<h1>섹션1</h1>
</section>
<section>
<h1>섹션2</h1>
</section>
<section>
<h1>섹션3</h1>
</section>
<section>
<h1>섹션3</h1>
</section>
</div>
</body>
</html>
CSS
더보기
header{
display: flex;
width: 800px;
align-items: center;
justify-content: center;
background-color: #333333;
color: white;
position: fixed;
top: 0;
left: 50%;
transform: translateX(-50%);
height: 100px;
padding: 10px;
border-bottom: 1px solid #ccc;
}
ul{
display: flex;
list-style: none
}
li{
margin-left: 1rem;
}
li:hover{
cursor: pointer;
transform: scale(1.1);
}
a{
text-decoration: none;
color: white;
}
a:hover{
cursor: pointer;
transform: scale(0.2);
color: antiquewhite;
transition: color 0.3s ease;
}
section{
margin: 0 auto;
background-color: #333333;
width: 700px;
height: 300px;
color: white;
}
#section1{
margin-top: 140px;
}
GitHub
https://github.com/IdoCleanCode/WebPageComponents/tree/master/Header/Fixed%20Header