본문 바로가기
03. 웹 표준 기술/CSS

[CSS] 05. Flex 스타일

by moca7 2024. 8. 7.

 

 

ㅁ display: flex;

- display로 인라인 요소를 블럭 요소로, 블럭 요소를 인라인 요소로, 인라인 요소와 블럭 요소의 특징을 다 가지게 할 수 있었다.

- display: flex를 요즘 많이 쓴다.

 

- 부모 컨테이너에 display: flex; 설정시 자식 컨테이너들은 flexible item이 된다. 

 

- 컨테이너는 (html)요소을 의미한다.

 

 

 

 

ㅁ 용어 

- CSS에서 부모 요소에 display: flex를 설정하면,  부모 요소 flex 컨테이너가 되고,

이 부모 요소의 자식 요소들은 자동으로 flex 아이템이 됩니다.

 

(1) 부모 : flex container

- 이 컨테이너는 자식 요소들의 배치와 정렬을 제어하는 역할을 합니다.

 

(2)  자식 : flex item

- flexbox 레이아웃 규칙을 적용받게 되며, 이로 인해 다음과 같은 특성을 가집니다:

 

  • 기본적으로 수평으로 배치됩니다(단, flex-direction 속성에 따라 수직으로도 배치할 수 있습니다).
  • flex 속성을 사용하여 크기와 비율을 조정할 수 있습니다.
  • 컨테이너의 크기에 따라 자동으로 조정될 수 있습니다.

 

 

ㅁ 메인축, 교차축

 

- 메인축(x축) : 수평 방향      main axis

- 교차축(y축) : 수직 방향      cross axis

 

 

 

 
        <div class="wrap1">
            <div class="box">box1</div>
            <div class="box">box2</div>
            <div class="box">box3</div>
        </div>
 
 
        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }
       
        .wrap1 {
            width: 600px;
            height: 200px;
        }
 

 

 

 

 
        .wrap1 {
            width: 600px;
            height: 200px;
            display: flex;
        }
 

 

 


- flex를 주니 수평으로 배치가 됨.

- 기본적으로 상위 요소에 display: flex 주는 순간 하위 요소들이 item이 됨.

- item들은 기본적으로 메인축(x축) 방향으로 정렬이 됨.

높이 부분이 부모요소의 100%가 되게끔 늘어남.

 

 

 

 
        .wrap1 {
            width: 600px;
            height: 200px;
            display: flex;
        }
        .wrap1 > .box {
            width: 50px;
            height: 50px;
        }
 

 

 

        .wrap1 > .box {
            width: 30%;
            height: 50%;
        }

- %단위로 주면 각각 부모 가로의 30%, 부모 세로의 50%를 차지하게 된다. 

 

 

 

 

 

ㅁ flex-direction

- item들의 배치 방향을 변경하는 스타일 속성

- 메인축을 지정하는 방식

 

(1) flex-direction : row;                                     수평방향(기본값)

(2) flex-direction : row-reverse;                        수평 역방향

(3) flex-direction : column;                               수직방향

(4) flex-direction : column-reverse;                  수직 역방향

 

- 수평방향일 경우 메인축은 x축, 교차축은 y축으로 지정한다.

- 수직방향일 경우 메인축은 y축, 교차축은 x축으로 지정한다.

 

 
        <div class="wrap2" id="row">
            <div class="box">box1</div>
            <div class="box">box2</div>
            <div class="box">box3</div>
        </div>
        <div class="wrap2" id="row-reverse">
            <div class="box">box1</div>
            <div class="box">box2</div>
            <div class="box">box3</div>
        </div>
        <div class="wrap2" id="column">
            <div class="box">box1</div>
            <div class="box">box2</div>
            <div class="box">box3</div>
        </div>
        <div class="wrap2" id="column-reverse">
            <div class="box">box1</div>
            <div class="box">box2</div>
            <div class="box">box3</div>
        </div>
 
 
        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }

        .wrap2 {
            width: 200px;
            height: 200px;
            margin-bottom: 20px; /* 아래쪽과 좀 띄워 줌 */
        }

        .wrap2 > .box {
            width: 50px;
            height: 50px;
        }
 

 

 

        .wrap2 {
            width: 200px;
            height: 200px;
            margin-bottom: 20px; /* 아래쪽과 좀 띄워 줌 */
            display: flex;
        }

 

 

- flex해서 수평 정렬됨.

 

 

 

        #row{
            flex-direction: row; /* 변함없음(기본값) */
        }
        #row-reverse{
            flex-direction: row-reverse;
        }
        #column{
            flex-direction: column;
        }
        #column-reverse{
            flex-direction: column-reverse;
        }

 

- 컨테이너 내에 아이템을 배치할 때 그 배치방법을 지정할 수 있다.

 

 

 

 

ㅁ flex-wrap

- item들이 container 범위에 벗어날 경우 처리할 방법을 지정

 

(1) flex-wrap: nowrap; (기본값)

- item들을 single-line으로 배치한다.

- container 밖으로 삐져나올 수 있음.

- nowrap하면 item의 크기가 내가 지정한 크기에서 변경될 수 있다.

 

(2) flex-wrap: wrap;

- item들을 multi-line으로 배치한다.

- container 밖으로 삐져나가지 않음.

- wrap하면 item의 크기가 내가 지정한 크기로 유지된다.

 

 
    <div class="wrap3" id="nowrap">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
        <div class="box">box4</div>
        <div class="box">box5</div>
        <div class="box">box6</div>
    </div>
 
    <div class="wrap3" id="wrap">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
        <div class="box">box4</div>
        <div class="box">box5</div>
        <div class="box">box6</div>
    </div>
 
 
        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }

        .wrap3 {
            width: 200px;
            height: 300px;
            margin-bottom: 20px;
        }

        .wrap3 > .box {
            width: 80px;
            height: 80px;
        }
 

 

 

 

 

 

        .wrap3 {
            width: 200px;
            height: 300px;
            margin-bottom: 20px;
           
            display: flex;
        }

 

- display:flex;를 하니까 각각 박스마다 가로 크기가 변경되었다. 80px이 아님. 그리고 컨테이너 밖으로 삐져나가 있음.

 

 

 

        #nowrap {
            flex-wrap: nowrap; /* 기본값 */
        }
   
        #wrap {
            flex-wrap: wrap;
        }
       

 

- wrap하니 아이템의 크기도 달라짐

 

 

 

 

ㅁ flex-flow

- flex-direction과 flex-wrap 속성을 함께 표기할 수 있는 단축 속성

- flex-flox: flex-direction flex-wrap;

 

- flex-direction, flex-wrap, flex-flow 전부 부모 컨테이너에 작성한다.

 


    <div class="wrap4">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
        <div class="box">box4</div>
        <div class="box">box5</div>
        <div class="box">box6</div>
    </div>    
   
 
        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }
        .wrap4 {
            width: 200px;
            height: 300px;
        }
        .wrap4 > .box {
            width: 80px;
            height: 80px;
        }
       

 

 

        .wrap4 {
            width: 200px;
            height: 300px;
 
            display: flex;
        }

 

 

 

        .wrap4 {
            width: 200px;
            height: 300px;
            display: flex;
           
            flex-flow: row wrap;
        }

 

 

 

 

 

ㅁ 아이템 정렬

- 기본적으로 아이템이 왼쪽에 붙어 있는데 가운데나 오른쪽 정렬.

- 부모 컨테이너에 display:flex를 매겨놓고 줘야하는 스타일 속성들이다.

 

 

ㅁ justify-content

- 메인축(direction이 row일 경우 x축, dircetion이 column일 경우 y축) 기준으로 정렬

- 메인축에 대한 정렬 방식.

 

 

(1) justify-content: flex-start;                        기본값. item들이 시작 지점에 모임.

(2) justify-content: flex-end;                         item들이 종료 지점(끝)에 모임.

(3) justify-content: center;                            item들이 가운데 지점에 모임.

 

(4) justify-content: space-between;              item들 사이에 공백이 추가됨.

(5) justify-content: space-around;                item들 마다 앞 뒤에 공백이 추가됨.

(6) justify-content: space-evenly;                 item들 사이에 균일한 공백이 추가됨.

 

 
    <div class="wrap5" id="flex-start">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap5" id="flex-end">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap5" id="center">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap5" id="space-between">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap5" id="space-around">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap5" id="space-evenly">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
 
 
        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }

        .wrap5 {
            width: 300px;
            height: 100px;
            margin-bottom: 10px;
            display: flex;
        }

        .wrap5 > .box {
            width: 50px;
            height: 50px;
        }

        .wrap5#flex-start { justify-content: start; }
        .wrap5#flex-end { justify-content: end; }
        .wrap5#center { justify-content: center; }
       
        .wrap5#space-between { justify-content: space-between; }
        .wrap5#space-around { justify-content: space-around; }
        .wrap5#space-evenly { justify-content: space-evenly; }
 

 

 

- 4 양쪽 끝에 하나씩 붙고 사이에 공백

- 5 아이템의 앞 뒤에 일정한 공백을 추가. 

- 6 균일한 공백

 

 

 

 

ㅁ  아이템이 좀 내려왔으면 해서 교차축 기준으로 정렬시키기.

 

ㅁ align-items

- 교차축(direction이 row일 경우 y축, clolumn일 경우 x축) 기준으로 정렬 방식 지정

 

(1) align-items: flex-start;

(2) align-items: flex-end;

(3) align-items: center;

 

(4) align-items: stretch;                           교차축 방향으로 item의 크기가 늘어남 

(5) align-items: baseline;                        baseline 기준으로 정렬

 

 
    <div class="wrap6" id="flex-start">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap6" id="flex-end">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap6" id="center">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap6" id="stretch">
        <div class="box">box1</div>
        <div class="box">box2</div>
        <div class="box">box3</div>
    </div>
    <div class="wrap6" id="baseline">
        <div class="box">box1</div>
        <div class="box" style="font-size: 30px;">box2</div> <!-- 티 나게 하려고 -->
        <div class="box">box3</div>
    </div>

 
        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }

        .wrap6 {
            width: 300px;
            height: 100px;
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
        }

        .wrap6 > .box{
            width: 70px;
        }

        .wrap6#flex-start {align-items: flex-start;}
        .wrap6#flex-end {align-items: flex-end;}
        .wrap6#center {align-items: center;}

        .wrap6#stretch {align-items: stretch;} /* 기본값 */
        .wrap6#baseline {align-items: baseline;}
 

 

 

 

- 특정 요소를 부모의 가운데에 두려면 부모에 dispaly:flex하고, justi 센터, align 센터 주면 된다.

 

 

 

        .wrap6 {
            width: 300px;
            height: 100px;
            margin-bottom: 20px;
            display: flex;
            justify-content: center;

            /* 아이템들간의 간격 주고싶을 때. space어쩌구 필요없이 gap만으로 가능 */
            gap:10px
        }

 

 

 

 

ㅁ 이번엔 아이템에 스타일을 부여함.

- 아이템들은 기본적으로 flex-basis(기본길이)보다 더이상 커지진 않고 대신 작아질 수 있다.

 

 

차이점 요약

  1. 적용 대상:
    • width는 일반적인 CSS 속성으로, Flex container와 관계없이 모든 요소에 적용될 수 있습니다.
    • flex-basis는 Flexbox 컨테이너 내의 Flex item에만 적용됩니다.
  2. 용도:
    • width는 단순히 요소의 너비를 설정합니다.
    • flex-basis는 Flex item의 초기 크기를 설정하며, 이후 flex-grow와 flex-shrink 속성에 의해 조정될 수 있습니다.

 

 

 

(1) flex-basis

- item 요소의 기본 길이를 의미한다.

 

(2) flex-grow

- 컨테이너 사이즈가 커질수록 item의 사이즈도 같이 커지게 할건지 여부 지정 (기본길이가 있지만 더 커지게)

- flex-grow: 0;          기본값. felx-basis보다 더 커지지 않음.

- flex-grow: 1;          컨테이너 사이즈가 커질수록 item 사이즈도 같이 커진다.

 

(3) flex-shrink

- 컨테이너 사이즈가 작아질수록 item의 사이즈도 같이 작아지게 할건지 여부 지정

- flex-shrink: 0;         flex-basis보다 더 이상 작아지지 않겠다는걸 의미.

- flex-shrink: 1;         기본값. 컨테이너 사이즈가 작아질수록 item 사이즈도 같이 작아진다.

 

 

(4) flex

- flex-basis, flex-grow, flex-shrink를 한번에 지정할 수 있는 단축 속성.

- flex: flex-grow flex-shrink flex-basis;

 

    <div class="wrap7">
        <div class="box1">box1</div>
        <div class="box2">box2</div>
        <div class="box3">box3</div>
    </div>

 

        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }

        .wrap7 {
            height: 100px;
            display: flex;
        }
        .wrap7 > div {
            width: 200px;
        }

 

 

 

 
        .wrap7 > div {
            width: 200px;
            flex-basis: 200px;/* flex-basis로도 가로길이 지정 가능. 최대 200까진 가능 감소는 됨. 이게 기본값 */
        }

 

창을 줄이면 아이템의 가로 길이도 줄어든다

 

- width는 무시됨.

 

 

 

        .wrap7 > div {
            width: 200px;
            flex-basis: 200px;/* flex-basis로도 가로길이 지정 가능. 최대 200까진 가능 감소는 됨. 이게 기본값 */
            flex-grow: 1;
        }

 

 

 

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>

    <style>
        div {
            box-sizing: border-box;    
            border : 1px solid gray;
        }

        .wrap7 {
            height: 100px;
            display: flex;
        }
        .wrap7 > div {
            flex-basis: 200px;/* flex-basis로도 가로길이 지정 가능. 최대 200까진 가능 감소는 됨. 이게 기본값 */
            flex-grow: 1;
            flex-shrink: 0;
        }

    </style>

</head>
<body>

    <div class="wrap7">
        <div class="box1">box1</div>
        <div class="box2">box2</div>
        <div class="box3">box3</div>
    </div>

</body>
</html>

 

 

- 선생님 실행결과도 같음. 브라우저가 창을 좁게하는데에 제한이 걸려있어서 그런듯.

- 작아지면 안되는데 작아짐. 브라우저때매 어쩔수 없는듯.

 

브라우저 창의 너비가 줄어들 때 flex-shrink: 0 설정 때문에 박스들이 축소되지 않습니다. 이로 인해 box1, box2, box3 모두가 축소되지 않으려 합니다. 그러나 실제로는 다음과 같은 문제가 발생합니다:

  • 전체 너비가 부족할 때: 브라우저의 너비가 줄어들면서 박스들이 크기를 유지하려고 하며, 만약 총 너비가 박스들의 기본 너비 합계보다 작다면, 실제로 브라우저는 박스의 기본 크기(200px x 3 = 600px)를 모두 보여줄 수 없습니다. 이 경우, 브라우저 창의 크기가 부족하게 되면 실제 렌더링에서는 박스들이 서로 겹치거나 레이아웃이 깨질 수 있습니다.

 

 

- 가로길이가 flex-basis보다 더 작아지진 않음.

- flex: 1 0 200px; 로 대체 가능.

 

 

        .wrap7 > div {
            flex-basis: 200px;/* flex-basis로도 가로길이 지정 가능. 최대 200까진 가능 감소는 됨. 이게 기본값 */
            flex-shrink: 1;
        }

 

 

- 브라우저를 줄이면 같이 작아진다.

 

 

 

 

ㅁ 개발자 도구탭 f12

 

 

- 개발자 도구 탭에서 flex 옆의 아이콘 누르면 미리보기로 테스트해볼 수 있어서 유용하다.

- 숫자 변경도 가능하다.

 

 

ㅁ 화면 작업을 할 때는 항상 레이아웃을 먼저 잡는다. 큰 틀 먼저 잡고 헤더, 컨텐츠, 푸터로 나누고 그 안에 또 나누고, 그 안의 요소. 큰것부터 -> 작은것 순서로 개발.

 

 

 

'03. 웹 표준 기술 > CSS' 카테고리의 다른 글

[css] 마무리  (0) 2024.08.08
[CSS] 04. 레이아웃 스타일  (0) 2024.08.07
[CSS] 04. 레이아웃 스타일  (0) 2024.08.06
[CSS] 실습문제  (0) 2024.08.06
[CSS] 테이블 관련 스타일  (0) 2024.08.06