Flex Box (CSS)

Photo by Andrew Neel on Unsplash

Flex Box (CSS)

Table of contents

No heading

No headings in the article.

Flexbox is a powerful CSS layout module that provides a flexible way to arrange and align elements within a container. It allows you to create responsive and dynamic layouts with ease. The flexbox model consists of a flex container and its flex items.

To use Flexbox, you need to apply the following properties to the parent container (flex container):

  1. display: flex; - This property is used to define a flex container. It enables the flexbox behavior for the container and its child elements.

Optional properties for the flex container:

  1. flex-direction: row; - This property determines the direction of the main axis (the primary axis along which flex items are laid out) within the flex container. The default value is row, which arranges items from left to right. Other possible values include column, row-reverse, and column-reverse.

  2. justify-content: flex-start; - This property aligns the flex items along the main axis. The default value is flex-start, which positions items at the start of the container. Other possible values include flex-end, center, space-between, space-around, and space-evenly.

  3. align-items: stretch; - This property aligns the flex items along the cross axis (the perpendicular axis to the main axis). The default value is stretch, which stretches the items to fill the container. Other possible values include flex-start, flex-end, center, and baseline.

Optional properties for individual flex items:

  1. flex-grow: 0; - This property specifies how much the flex item can grow relative to other items if there's extra space along the main axis. By default, it's set to 0, meaning the item won't grow.

  2. flex-shrink: 1; - This property specifies how much the flex item can shrink relative to other items if there's not enough space along the main axis. By default, it's set to 1, allowing the item to shrink.

  3. flex-basis: auto; - This property specifies the initial size of the flex item along the main axis before any remaining space is distributed. The default value is auto, which means the item's size is based on its content.

  4. It is easier to center the div using Flexbox

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

These are just a few of the most commonly used properties in Flexbox. There are several other properties and values available to fine-tune the layout and achieve more complex arrangements. Flexbox is widely supported in modern browsers and is a popular choice for building responsive and flexible layouts in CSS.