Table of contents
Flexbox is a one-dimensional layout method for arranging items in rows or columns. Items flex (expand) to fill additional space or shrink to fit into smaller spaces. This article explains all the fundamentals.
Flex Container
The Flex container is the parent element that contains one or more Flex items. To create a Flex container, you need to set the display property to flex or inline-flex.
.container {
display: flex;
}
By default, the Flex container aligns its items horizontally (in a row), but you can also set the flex-direction property to column to align the items vertically (in a column).
.container {
display: flex;
flex-direction: column;
}
Flex Items
Flex items are the child elements inside the Flex container. You can apply Flexbox properties to these items to control their size, position, and alignment. By default, Flex items have a flex-grow value of 0, which means they won't grow to fill the available space.
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
.container {
display: flex;
}
.item {
/* Flex item properties go here */
}
Flex Properties
Flex properties are used to control the layout of Flex items within the Flex container. Here are some of the most commonly used Flex properties:
-flex-grow: Specifies how much the Flex item can grow relative to other Flex items in the container. By default, it's set to 0, which means the item won't grow.
-flex-shrink: Specifies how much the Flex item can shrink relative to other Flex items in the container. By default, it's set to 1, which means the item will shrink if necessary.
flex-basis: Specifies the initial size of the Flex item before any growing or shrinking occurs.
flex: A shorthand property that combines flex-grow, flex-shrink, and flex-basis into one declaration.
justify-content: Aligns Flex items along the main axis (horizontal for row and vertical for column).
align-items: Aligns Flex items along the cross axis (vertical for row and horizontal for column).
order: The order property accepts a numeric value that determines the order of the Flex item within the Flex container.
align-self: Aligns a specific Flex item along the cross axis (overrides the align-items property).
Flexbox Example
Resources
MDN docs — Documention explaining fundamentals of Flexbox
CSS-Tricks Guide to Flexbox — an article explaining everything about Flexbox in a visually appealing way
Flexbox Froggy — an educational game to learn and better understand the basics of Flexbox