HTML&CSS

flex 를 이용해 자식 요소를 브라우저 높이(height: 100%)에 따라 내부 스크롤 자동 생성

woox 2023. 12. 31. 18:27

보통 스크롤이 없는 height 100% 페이지를 구현하다 보면

내부에 컨텐츠가 많아져 내부 스크롤바가 필요할 경우가 있다.

 

이론적으로는 flex 를 사용하면 당연히 가능할 것 같은데 막상 구현하다 보면 생각과는 다르게 동작하지 않는 경우가 있다

기본적인 구조는 아래와 같이 구현할 경우

<style>
	html, body {height: 100%;margin: 0;font-size: 20px;}
	main {display: flex;flex-direction: column;flex: 1 1 auto;background: purple;height: 100%;}
	header {
		flex: 0 0 80px;
		background: #FFAEAE;
	}
	section {
		flex: 1 1 auto;
		display: flex;
		flex-direction: column;
		background: #EAE9E9;
	}
	section h2 {flex: 0 0 auto;}
	section .scroll_content {flex: 1 1 auto;overflow-y: auto;background: #D9D9D9;}
	footer {
		flex: 0 0 80px;
		background: #BEFFAE;
	}
</style>
<main>
	<header>헤더</header>
	<section>
		<h2>컨텐츠</h2>
		<div class="scroll_content">
			내용이 늘어나서 줄이 길어 집니다.<br>
			내용이 늘어나서 줄이 길어 집니다.<br>
            ............
		</div>
	</section>
	<footer>푸터</footer>
</main>

위와 같이 구현할 것이다.

 

한데 flex 로 이루어진 레이아웃 안에서 다시 flex 를 이용해 자식요소를 flex-basis: auto 를 이용해

고정 pixel 이 아닌 auto 로 여백을 채울경우 제대로 동작하지 않는다.

 

See the Pen flex 내부 flex 로 height : auto 및 scrollbar by woox (@woox-styler) on CodePen.

 

단순한 flex 레이아웃일 경우 잘 동작하지만 flex flex-basis: auto (height: 100%)안에서 다시 flex flex-basis: auto 일 경우 제대로 동작하지 않는다.

이때, flex-basis: auto 인 요소에 min-height: 0 을 주면 원하는 대로 잘 동작한다.

<style>
	html, body {height: 100%;margin: 0;font-size: 20px;}
	main {display: flex;flex-direction: column;flex: 1 1 auto;background: purple;height: 100%;}
	header {
		flex: 0 0 80px;
		background: #FFAEAE;
	}
	section {
		flex: 1 1 auto;
		display: flex;
		flex-direction: column;
		background: #EAE9E9;
		min-height: 0;
	}
	section h2 {flex: 0 0 auto;}
	section .scroll_content {flex: 1 1 auto;overflow-y: auto;background: #D9D9D9;}
	footer {
		flex: 0 0 80px;
		background: #BEFFAE;
	}
</style>
<main>
	<header>헤더</header>
	<section>
		<h2>컨텐츠</h2>
		<div class="scroll_content">
			내용이 늘어나서 줄이 길어 집니다.<br>
			내용이 늘어나서 줄이 길어 집니다.<br>
            ..................
		</div>
	</section>
	<footer>푸터</footer>
</main>

 

 

See the Pen flex 내부 flex 로 height : auto 및 scrollbar - min-height: 0; by woox (@woox-styler) on CodePen.

기본적으로 min-height 값은 auto 인데 이게 flex-basis 보다 우선적으로 적용되기 때문에 일어나는 현상이다.

나는 height 를 기준으로 예를 들었지만 width 즉 가로 형태에서도 동일하다 그때엔 min-width: 0을 주면 된다