Computer >> 컴퓨터 >  >> 프로그래밍 >> CSS

CSS3 플렉스박스(Flexbox) 레이아웃 완벽 가이드

CSS3 플렉스박스(Flexbox)란?

CSS3는 '플렉시블 박스(Flexible Box)', 흔히 플렉스박스(Flexbox)라고 불리는 강력한 레이아웃 모드를 제공합니다. 플렉스박스를 활용하면 복잡한 구조의 웹 애플리케이션이나 웹 페이지 레이아웃도 손쉽게 구성할 수 있습니다.

플렉스박스 레이아웃은 컨테이너(container)와 그 안에 배치되는 플렉스 아이템(flex items)으로 구성됩니다. 컨테이너에는 다음과 같은 주요 속성들이 사용됩니다.

  • flex-direction — 플렉스 아이템의 배치 방향(가로/세로)을 지정합니다.

  • flex-wrap — 아이템이 한 줄에 담기지 않을 때 줄바꿈 여부를 결정합니다.

  • flex-flow — flex-direction과 flex-wrap을 한 번에 설정하는 축약 속성입니다.

  • justify-content — 주축(main axis) 방향으로 아이템들을 정렬합니다.

  • align-items — 교차축(cross axis) 방향으로 아이템들을 정렬합니다.

  • align-content — 여러 줄로 나뉜 플렉스 라인 전체를 정렬합니다.

플렉스박스 레이아웃 예제

다음은 CSS3의 플렉스박스를 활용해 다양한 정렬 방식을 구현한 코드입니다.

<!DOCTYPE html>
<html>
<head>
<style>
body {
   font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.container {
   display: flex;
   flex-wrap: wrap;
   justify-content: space-evenly;
   background-color: lightblue;
}
.container1 {
   align-self: flex-start;
   display: flex;
   background-color: rgb(71, 30, 255);
   width: 200px;
   margin: 20px;
}
.container1 > div,
.container2 > div,
.container3 > div,
.container4 > div {
   background-color: #f1f1f1;
   margin: 10px;
   padding: 10px;
   font-size: 30px;
}
.container2 {
   display: flex;
   background-color: rgb(14, 126, 79);
   width: 200px;
   justify-content: center;
   align-self: flex-start;
   margin: 20px;
}
.container3 {
   display: flex;
   flex-direction: column;
   background-color: rgb(168, 60, 10);
   width: 200px;
   align-items: center;
   margin: 20px;
}
.container4 {
   background-color: rgb(26, 10, 168);
   width: 200px;
   margin: 20px;
}
</style>
</head>
<body>
<h1>Flex layout example</h1>
<div class="container">
<div class="container1">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="container2">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="container3">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
<div class="container4">
<div>1</div>
<div>2</div>
<div>3</div>
</div>
</div>
</body>
</html>

실행 결과

위 코드를 실행하면 네 개의 서로 다른 플렉스 컨테이너가 화면에 균등하게 배치된 것을 확인할 수 있습니다. 각 컨테이너는 기본 정렬, 중앙 정렬, 세로(column) 방향 정렬 등 서로 다른 플렉스 속성 조합을 보여주며, 이를 통해 플렉스박스가 얼마나 유연하게 레이아웃을 제어할 수 있는지 직관적으로 이해할 수 있습니다.