We're looking for a user researcher to understand the needs of developers and designers. Is this you or someone you know? Check out the post: https://mzl.la/2IGzdXS

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

보통 flexbox로 불리는 Flexible Box 모듈은, 1차원적인 레이아웃 모델이자 인터페이스와 강력한 정렬 기능을 통해 항목 간 공간 배분을 제공할 수 있는 방법으로 설계되었습니다. 이 글에서는 flexbox의 핵심 특징들의 개요를 다룹니다. 더 자세한 내용들은 가이드의 나머지 부분들에서 탐구하게 될 것입니다.

flexbox를 1차원적이라고 할 때에는, flexbox가 레이아웃의 각 차원을 — 행이나 열과 같이 — 각각 다룬다고 봅니다. 이는 행과 열을 함께 조절하는 CSS 그리드 레이아웃의 2차원 모델과는 대조됩니다.

flexbox의 두개의 축

flexbox로 작업할 때에는 두개의 축 — 주축과 교차축 — 을 생각해야 합니다.  주축은 flex-direction 속성에 의해 정의되고, 교차축은 이에 수직입니다. flexbox로 하는 모든 것들이 이 축을 참조하기 때문에 이들이 어떻게 동작하는지를 처음부터 이해하는 것이 중요합니다.

주축

주축은 flex-direction에 의해 정의되고 4개의 값을 가질 수 있습니다:

  • row
  • row-reverse
  • column
  • column-reverse

row 혹은 row-reverse를 선택하면, 주축은 인라인 방향으로 행을 따릅니다.

If flex-direction is set to row the main axis runs along the row in the inline direction.

column 혹은 column-reverse 을 선택하면 주축은 페이지의 상단부터 하단 — 블록 방향 — 을 향합니다.

If flex-direction is set to column the main axis runs in the block direction.

교차축

교차축은 주축에 수직하므로, 만약 flex-direction (주축)이 row 나 row-reverse 라면 교차축은 열 방향을 따릅니다.

If flex-direction is set to row then the cross axis runs in the block direction.

주축이 column 혹은 column-reverse 이면 교차축은 행 방향을 따릅니다.

If flex-direction is set to column then the cross axis runs in the inline direction.

flex 항목들을 정렬하고 맞추는 것을 보기 시작하면, 어느 축이 더 중요한지를 이해하는 것은 flexbox가 특히 한 축과 다른 축을 따라 컨텐츠를 정렬하고 맞추는 속성을 특징으로 갖는다는 것과 관계됩니다.

시작과 끝 선

또 다른 필수적인 이해는 어떻게 flexbox가 문서의 쓰기 방법에 대해 가정을 하지 않는가 하는 것입니다. 과거에는, CSS는 수평 방향이면서 왼쪽에서 오른쪽으로 쓰는 형태에 치우쳐 있었습니다.  현대의 레이아웃 수단들은 넓은 범위의 쓰기 방법들을 아우르고 있기 때문에 우린 더이상 텍스트 라인이 왼쪽 위에서 오른쪽 아래로 향한다고 가정하지 않습니다, 새 라인이 다른 라인의 아래에 나타난다는 점을 포함해서요.

flexbox과 쓰기 방법의 관계에 대한 자세한 내용을 이후에 볼 수 있지만, 다음의 설명은 왜 더이상 flex 항목들이 향하는 방향을 왼쪽에서 오른쪽으로, 위에서 아래로 설명하지 않는지 이해하는 데에 도움이 됩니다.

만약 flex-direction 이 row 이면 영어로 동작하고 있는 것이고 주축은 왼쪽 끝에서 시작해서 오른쪽 끝에서 끝납니다.

Working in English the start edge is on the left.

아랍어로 동작한다면, 주축은 오른쪽 끝에서 시작해서 왼쪽 끝에서 끝날 것입니다.

The start edge in a RTL language is on the right.

두 언어가 가로 쓰기 모드이기 때문에, 두 예시 모두 교차축은 flex 컨테이너의 위에서 시작해서 아래에서 끝납니다.

잠시 후에, 왼쪽과 오른쪽 보다 시작과 끝으로 생각하는 것이 동일한 패턴을 따르는 CSS 그리드 레이아웃과 같은 다른 레이아웃 수단을 다룰 때에 더 자연스럽고 유용한 지에 대해 생각합니다. 

flex 컨테이너

flexbox가 놓여있는 문서의 영역을 flex 컨테이너라고 부릅니다. flex 컨테이너를 만들이 위해서, 영역의 컨테이너의 display 값을 flex 혹은 inline-flex로 설정합니다. 이렇게 하면 컨테이너의 자식은 flex 항목이 됩니다. CSS의 모든 속성들처럼, 일부 초기값이 정의됩니다, 따라서 flex 컨테이너를 생성할 때 포함된 모든 flex 항목들은 다음과 같이 동작합니다.

  • 항목들은 행으로 보여집니다. (flex-direction 속성의 기본값은 row입니다).
  • 항목들은 주축의 시작점으로부터 시작합니다.
  • 항목들은 주 차원 위에서 늘어나지는 않지만, 줄어들 수는 있습니다.
  • 항목들은 교차축의 크기를 채우기 위해 늘어납니다.
  • flex-basis 속성을 auto로 설정합니다.
  • flex-wrap 속성을 nowrap으로 설정합니다.

이 결과로 항목들은 주축에서의 사이즈를 사용해서 행을 따라 나열됩니다. 만약 컨테이너에 맞출 수 있는 것 보다 더 많은 항목들이 있으면 오버플로우됩니다. 만약 특정 항목이 다른 것들보다 높으면 모든 항목들이 전체 사이즈를 채우기 위해 교차축을 따라 늘어납니다.

어떻게 보여지는지 다음의 라이브 예시를 통해 볼 수 있습니다. flexbox의 초기 동작을 시험해보기 위해 항목을 추가하거나 수정해보시기 바랍니다.

 

Changing flex-direction

Adding the flex-direction property to the flex container allows us to change the direction in which our flex items display. Setting flex-direction: row-reverse will keep the items displaying along the row, however the start and end lines are switched.

If we change flex-direction to column the main axis switches and our items now display in a column. Set column-reverse and the start and end lines are again switched.

The live example below has flex-direction set to row-reverse. Try the other values — row, column and column-reverse — to see what happens to the content.

Multi-line flex containers with flex-wrap

While flexbox is a one dimensional model, it is possible to cause our flex items to wrap onto multiple lines. In doing so, you should consider each line as a new flex container. Any space distribution will happen across that line, without reference to the lines either side.

To cause wrapping behaviour add the property flex-wrap with a value of wrap. Now, should your items be too large to all display in one line, they will wrap onto another line. The live sample below contains items that have been given a width, the total width of the items being too wide for the flex container. As flex-wrap is set to wrap, the items wrap. Set it to nowrap, which is also the initial value, and they will instead shrink to fit the container because they are using initial flexbox values that allows items to shrink. Using nowrap would cause an overflow if the items were not able to shrink, or could not shrink small enough to fit.

Find out more about wrapping flex items in the guide Mastering Wrapping of Flex Items.

The flex-flow shorthand

You can combine the two properties flex-direction and flex-wrap into the flex-flow shorthand. The first value specified is flex-direction and the second value is flex-wrap.

In the live example below try changing the first value to one of the allowable values for flex-direction - row, row-reverse, column or column-reverse, and also change the second to wrap and nowrap.

Properties applied to flex items

To have more control over flex items we can target them directly. We do this by way of three properties:

We will take a brief look at these properties in this overview, and you can gain a fuller understanding in the guide Controlling Ratios of Flex Items on the Main Axis.

Before we can make sense of these properties we need to consider the concept of available space. What we are doing when we change the value of these flex properties is to change the way that available space is distributed amongst our items. This concept of available space is also important when we come to look at aligning items.

If we have three 100 pixel-wide items in a container which is 500 pixels wide, then the space we need to lay out our items is 300 pixels. This leaves 200 pixels of available space. If we don’t change the initial values then flexbox will put that space after the last item.

This flex container has available space after laying out the items.

If we instead would like the items to grow and fill the space, then we need to have a method of distributing the leftover space between the items. This is what the flex properties that we apply to the items themselves, will do.

The flex-basis property

The flex-basis is what defines the size of that item in terms of the space it leaves as available space. The initial value of this property is auto — in this case the browser looks to see if the items have a size. In the example above, all of the items have a width of 100 pixels and so this is used as the flex-basis.

If the items don’t have a size then the content's size is used as the flex-basis. This is why when we just declare display: flex on the parent to create flex items, the items all move into a row and take only as much space as they need to display their contents.

The flex-grow property

With the flex-grow property set to a positive integer, flex items can grow along the main axis from their flex-basis. This will cause the item to stretch and take up any available space on that axis, or a proportion of the available space if other items are allowed to grow too.

If we gave all of our items in the example above a flex-grow value of 1 then the available space in the flex container would be equally shared between our items and they would stretch to fill the container on the main axis.

The flex-grow property can be used to distribute space in proportion. If we give our first item a flex-grow value of 2 and the other items a value of 1, 2 parts will be given to the first item (100px out of 200px in the case of the example above), 1 part each the other two (50px each out of the 200px total).

The flex-shrink property

Where the flex-grow property deals with adding space in the main axis, the flex-shrink property controls how it is taken away. If we do not have enough space in the container to lay out our items and flex-shrink is set to a positive integer the item can become smaller than the flex-basis. As with flex-grow different values can be assigned in order to cause one item to shrink faster than others — an item with a higher value set for flex-shrink will shrink faster than its siblings that have lower values.

The minimum size of the item will be taken into account while working out the actual amount of shrinkage that will happen, which means that flex-shrink has the potential to appear less consistent than flex-grow in behavior. We’ll therefore take a more detailed look at how this algorithm works in the article Controlling Ratios of items along the main axis.

Note that these values for flex-grow and flex-shrink are proportions. Typically if we had all of our items set to flex: 1 1 200px and then wanted one item to grow at twice the rate, we would set that item to flex: 2 1 200px. However you could use flex: 10 1 200px and flex: 20 1 200px if you wanted.

Shorthand values for the flex properties

You will very rarely see the flex-grow, flex-shrink, and flex-basis properties used individually; instead they are combined into the flex shorthand. The flex shorthand allows you to set the three values in this order — flex-grow, flex-shrink, flex-basis.

The live example below allows you to test out the different values of the flex shorthand; remember that the first value is flex-grow. Giving this a positive value means the item can grow. The second is flex-shrink — with a positive value the items can shrink, but only if their total values overflow the main axis. The final value is flex-basis; this is the value the items are using as their base value to grow and shrink from.

There are also some predefined shorthand values which cover most of the use cases. You will often see these used in tutorials, and in many cases these are all you will need to use. The predefined values are as follows:

  • flex: initial
  • flex: auto
  • flex: none
  • flex: <positive-number>

Setting flex: initial resets the item to the initial values of Flexbox. This is the same as flex: 0 1 auto. In this case the value of flex-grow is 0, so items will not grow larger than their flex-basis size. The value of flex-shrink is 1, so items can shrink if they need to rather than overflowing. The value of flex-basis is auto. Items will either use any size set on the item in the main dimension, or they will get their size from the content size.

Using flex: auto is the same as using flex: 1 1 auto; everything is as with flex:initial but in this case the items can grow and fill the container as well as shrink if required.

Using flex: none will create fully inflexible flex items. It is as if you wrote flex: 0 0 auto. The items cannot grow or shrink but will be laid out using flexbox with a flex-basis of auto.

The shorthand you often see in tutorials is flex: 1 or flex: 2 and so on. This is as if you used flex: 1 1 0. The items can grow and shrink from a flex-basis of 0.

Try these shorthand values in the live example below.

Alignment, justification and distribution of free space between items

A key feature of flexbox is the ability to align and justify items on the main- and cross-axes, and to distribute space between flex items.

align-items

The align-items property will align the items on the cross axis.

The initial value for this property is stretch and this is why flex items stretch to the height of the tallest one by default. They are in fact stretching to fill the flex container — the tallest item is defining the height of that.

You could instead set align-items to flex-start in order to make the items line up at the start of the flex container, flex-end to align them to the end, or center to align them in the centre. Try this in the live example — I have given the flex container a height in order that you can see how the items can be moved around inside the container. See what happens if you set the value of align-items to:

  • stretch
  • flex-start
  • flex-end
  • center

justify-content

The justify-content property is used to align the items on the main axis, the direction in which flex-direction has set the flow. The initial value is flex-start which will line the items up at the start edge of the container, but you could also set the value to flex-end to line them up at the end, or center to line them up in the centre.

You can also use the value space-between to take all the spare space after the items have been laid out, and share it out evenly between the items so there will be an equal amount of space between each item. To cause an equal amount of space on the right and left of each item use the value space-around. With space-around, items have a half-size space on either end. Or, to cause items to have equal space around them use the value space-evenly. With space-evenly, items have a full-size space on either end.

Try the following values of justify-content in the live example:

  • stretch
  • flex-start
  • flex-end
  • center
  • space-around
  • space-between
  • space-evenly

In the article Aligning Items in a Flex Container we will explore these properties in more depth, in order to have a better understanding of how they work. These simple examples however will be useful in the majority of use cases.

Next steps

After reading this article you should have an understanding of the basic features of Flexbox. In the next article we will look at how this specification relates to other parts of CSS.

문서 태그 및 공헌자

이 페이지의 공헌자: Latera
최종 변경: Latera,