Introduction to Flexbox

Get introduced to flexbox and learn flex properties like flex-direction, flex-wrap, and flex-flow

We'll cover the following

Flexbox does a superb job of centering multiple items and is also great at spacing items of different sizes. It’s not, however, very good at lining up rows and columns or keeping items in a structured grid format.

Columns, as we saw earlier, excel at making text columns, but can be unruly and difficult when laying out things other than text.

Flexbox came before CSS grid and has better browser support (although CSS grid has excellent browser support, too). Flexbox shines

  • when doing single rows/columns
  • for multiple rows when fine-grained control isn’t required
  • with objects of varying size

If you need pixel-perfect control over where elements are, flexbox will make you tear your hair out, but if your layout needs are more approximate or you have varying-sized items, flexbox is an excellent weapon of choice.

Flex properties

display: flex: This goes on the container element, which is the parent element of the items you want to organize. If you don’t have a container element, you need to create one.

.undead-parent {
    display: flex;
}

flex-direction: This sets how the elements are laid out, either as columns or rows, and sets the axes you’ll be using. Since it can change which direction acts as the block or inline direction, when working with flexbox, it’s best to call them the main-axis and the cross-axis. When flex-direction defines rows, the main-axis/direction is the inline direction. But when you change the flex-direction to columns, you change the main-axis to the block direction, while elements and text within your flex items still follow the default inline and block directions.

Since this can get more confusing than a zombie at a midnight showing of “Night of the Living Dead”, we’ll stick with the main-axis and cross-axis. Just remember that they can flip, depending on what you choose for the flex-direction. Also, for simplicity, we’ll assume that you’re using a left-to-right language such as English, making your inline direction left to right and your block direction up and down. If you’re using a different language or a different writing-direction, the directions will change.

.undead-parent {
    flex-direction: column;
}
  • column: Displays items vertically, starting with the first element at the top.

  • column-reverse: Displays items vertically, starting with the first element at the bottom.

  • row: Displays items horizontally, starting with the first element at the left.

  • row-reverse: Displays items horizontally, starting with the first element at the right.

Get hands-on with 1400+ tech skills courses.