본문 바로가기

HTML \ CSS \ JavaScript/CSS

[CSS] footer 하단에 고정하기

컨텐츠가 짧은 경우 푸터가 위로 올라와버리는 문제 발생.

<html>
<style>
html, body{height: 100%}
</style>
<body>

<header>Header</header>

<div class="contents">컨텐츠 내용</div>

<footer>
	<p>푸터입니다</p>
</footer>

</body>
</html>

 

footer{
	position: fixed;
	bottom: 0px;
}

fixed로 고정.

이 경우 푸터를 언제나 화면 하단에 고정할 수 있으나

만약 컨텐츠의 높이가 화면 사이즈를 넘는 경우

푸터가 컨텐츠를 가려 버리는 문제 발생

 

이를 해결하기 위해

html, body {height:100%}

html과 body에 높이를 100%를 줘서 화면 전체 높이를 가지게 하고

<div class="wrapper">
	<header>Header</header>
	<div class="contents">컨텐츠 내용<div>
</div>

<footer>Footer</footer>

헤더태그와 컨텐츠 태그를 div 태그로 감싼 뒤 (이 글에서는 wrapper 클래스)

.wrapper{
	height:auto;
	min-height: 100%;
	padding-bottom: 193px; // 현재 푸터의 높이
}

wrapper 클래스의 높이를 auto,

최소 높이를 100%를 줘서 화면 전체 높이를 가지게 하고

(컨텐츠가 없어도 윈도우 창 높이까지는 wrapper 클래스 영역으로 잡힘)

푸터의 높이만큼 패딩을 줘서 하단에 빈 공간을 만들어 준 뒤

footer{
height:193px; // 푸터의 높이
position: relative;
transform: translateY(-100%); // 높이의 100% 만큼 마이너스
}

그 아래 푸터의 포지션을 relative, transform을 줘서 푸터의 높이만큼 위로 올라오게 함

 

결과는

 

<html>
<style>
    html, body{height: 100%}
    .wrapper{
        height:auto;
        min-height: 100%;
        padding-bottom: 193px; // 현재 푸터의 높이
	}
    footer{
    	height:193px; // 푸터의 높이
    	position: relative;
    	transform: translateY(-100%); // 높이의 100% 만큼 마이너스
	}
</style>
<body>

<div class="wrapper">
	<header>Header</header>
	<div class="contents">컨텐츠 내용<div>
</div>

<footer>Footer</footer>

</body>
</html>

컨텐츠 높이가 낮을 때 > 푸터가 하단에 고정

컨텐츠 높이가 길 때 > 스크롤을 내려 컨텐츠 끝에 도달하면 그 아래 푸터가 붙어있음

 

이렇게 해결!

 

'HTML \ CSS \ JavaScript > CSS' 카테고리의 다른 글

[CSS] 화면 정중앙에 요소 배치(반응형)  (0) 2022.06.09