[CSS] Flexbox 개념 & 실전 예제 정리

YUMIN·2025년 5월 26일

HTML & CSS

목록 보기
10/14

👩🏼‍💻 FlexboxCSS의 레이아웃 구성 방식 중 하나로, 아이템을 가로 또는 세로 방향으로 정렬하고 배치하는 데 최적화되어 있다.


1️⃣ Flexbox 기본 구조

.container {
  display: flex; /* 또는 inline-flex */
}
  • flex → block 요소처럼 컨테이너가 전체 너비 차지
  • inline-flex → inline 요소처럼 콘텐츠 흐름에 따라 배치됨
  • 자식 요소는 기본적으로 가로 방향(main axis)으로 정렬됨

예제 코드 (ex01_flexbox.html)

<div class="flex-container flex">
  <div class="box">A</div>
  <div class="box">B</div>
  <div class="box">C</div>
</div>

2️⃣ flex-direction (주축 방향 설정)

flex-direction: row | row-reverse | column | column-reverse;
  • row (기본값): 좌 → 우
  • row-reverse: 우 → 좌
  • column: 위 → 아래
  • column-reverse: 아래 → 위

예제 코드 (ex02_flexbox.html)

<div class="flex-container column">
  <div class="box">A</div>
  <div class="box">B</div>
  <div class="box">C</div>
</div>

3️⃣ flex-wrap (줄 바꿈 여부)

flex-wrap: nowrap | wrap | wrap-reverse;
  • nowrap (기본값): 한 줄에 모든 아이템
  • wrap: 공간이 부족하면 다음 줄로 넘어감

예제 코드 (ex03_flexbox.html)

<div class="flex-container wrap">
  <div class="box">A</div>
  ...
</div>

4️⃣ 수직/수평 정렬

justify-content: center | space-between | space-around | flex-start | flex-end;
align-items: center | flex-start | flex-end | stretch | baseline;
  • justify-content: 주축 방향 정렬
  • align-items: 교차축 방향 정렬

예제 코드 (ex04_flexbox.html)

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

5️⃣ 화면 정중앙 정렬

전체 페이지의 가운데에 요소 정렬하기:

🔍 예제 코드 (ex05_center.html)

.wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

6️⃣ 메뉴 레이아웃에 flex 사용

고정되지 않은 메뉴 (menu1.html)

header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

고정 메뉴 바 (menu2~5.html)

header {
  position: fixed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  top: 0;
  width: 100%;
}

주의 : 고정된 메뉴바 때문에 body 또는 mainpadding-top을 추가해 콘텐츠가 가려지지 않게 해야 함


🧠 정리

속성설명
display: flexFlexbox 활성화
flex-direction주축 방향 설정
flex-wrap줄 바꿈 허용 여부
justify-content주축 정렬 방식
align-items교차축 정렬 방식
inline-flex인라인 컨테이너에 Flex 적용
fixed 메뉴고정된 UI 구현 시 활용

0개의 댓글