본문 바로가기

dev/CSS

CSS flexbox : 기본 개념

Created: Aug 4, 2020 3:15 PM
Reviewed: No

flexbox 기본 개념

아이템을 행,열 형태로 배치하는 일차원 레이아웃 메서드다.

grid는 2차원 레이아웃 입니다.

flexbox 설정

  • display : flex
  • display: inline-flex

flexbox 구성요소

  • main axis
  • cross axis
  • flex container
  • flex item

flex container

axis

main axis 정의는 flex-direction을 이용한다.

  • flex-direction : column | row (default) | column-reverse | row-reverse
.container {
    display:flex;
    flex-direction: column;
}

main axis의 반대 축이 cross axis가 된다.

wrap

flexbox 내부에서 아이템이 벗어나지 못하도록 한다. 벗어나는 아이템은 여러 행으로 나누어 표시된다.

  • flex-wrap : wrap | nowrap (default) | wrap-reverse
.container {
    display:flex;
    flex-direction: column;
    flex-wrap: wrap;
}

flex-direction + flex-wrap = flex-flow

  • flex-flow : flex-direction flex-wrap
.container {
    flex-direction : row;
    flex-wrap : wrap;
}

// 위와 동일
.container {
    flex-flow: row wrap;
}

정렬

기본적으로 container에 정렬 방식 부여

.container {
    display:flex;
    justify-content: space-around;
    align-items: center;
}

justify-content : main axis 기준 정렬

flex-start (default) | flex-end | center | space-around | space-between

align-items : cross axis 기준 정렬

stretch (default) | center | flex-start | flex-end

특별히 개별 항목에 대해 정렬 기준을 따로 부여하고 싶은 경우, item 레벨align-self 속성을 지정해 준다.

.container {
    display:flex;
    justify-content: space-around;
    align-items: center;
}

// 첫번째 item은 align-items가 flex-end가 된다.
.item:first-child {
    align-self: flex-end
}

 

flex item

flex item의 비율 조정

  • flex : 아래 3개를 합친 것!
  • flex-grow : item이 공간을 점유하는 비율
  • flex-shrink : item이 줄어드는 비율
  • flex-basis : item의 최소 크기
// 모든 item이 동등하게 공간 차지
.item {
    flex : 1;
}

// 3번째 item만 두 배로 공간을 차지
.item:nth-child(3) {
    flex: 2;
}
// 모든 item이 동등하게 공간 차지, 최소 크기는 200px
.item {
    flex : 1 200px;
}

// 3번째 item만 두 배로 공간을 차지, 최소 크기는 200px
.item:nth-child(3) {
    flex: 2 200px;
}

flex item의 정렬(cross axis)

align-self 를 통해 컨테이너의 align-items를 무시하고 cross axis 정렬을 할 수 있다.

.container {
    display:flex;
    justify-content: space-around;
    align-items: center;
}

// 첫번째 item은 align-items가 flex-end가 된다.
.item:first-child {
    align-self: flex-end
}

flex item의 순서

order : number 를 이용해 순서를 변경한다 (기본값 0, 음수 사용 가능)

  • 순위값이 작을수록 먼저 표시
  • 순위값이 같다면 소스 순서대로 표시