Flexbox in CSS

Flexbox is a CSS layout module that makes it simple to align and divide up space among elements inside of a container. It is a powerful tool for developing responsive layouts and can be used to make numerous layouts, such as multi-column, horizontal, and vertical layouts.

To use flexbox, you need to set the ‘display’ property of the container element to ‘flex’. This will make all of the direct children of the container flex items.

.container {
    display: flex;
}

Once the container is set to ‘display: flex’, you can use several different properties to control the alignment and distribution of the flex items. Some common ones include:

  • ‘flex-direction’: Controls the direction of the main axis. Possible values include ‘row’, ‘row-reverse’, ‘column’, and ‘column-reverse’.

  • ‘flex-wrap’: Controls whether flex items are allowed to wrap onto multiple lines. Possible values include ‘nowrap’, ‘wrap’, and ‘wrap-reverse’.

  • ‘justify-content’: Aligns flex items along the main axis (horizontally, by default). Possible values include ‘flex-start’, ‘center’, ‘flex-end’, ‘space-between’, and ‘space-around’.

  • ‘align-items’: Aligns flex items along the cross axis (vertically, by default). Possible values include ‘flex-start’, ‘center’, ‘flex-end’, ‘stretch’, and ‘baseline'.

  • ‘align-self’: Allows you to override the align-items value for a specific flex item.

Here is an example of using these properties to create a horizontal layout with items centered vertically and evenly distributed horizontally:

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

Another useful feature of flexbox is the ability to align items along the cross axis using the ‘align-content’ property. This property works similarly to ‘justify-content’, but it aligns flex lines (rows or columns of flex items) rather than individual items. Possible values include ‘flex-start’, ‘center’, ‘flex-end’, ‘space-between’, ‘space-around’, and ‘stretch’.