CSS Flexbox for Beginners [2022]

Flexbox helps you to align elements. It’s much easier and better than Float etc

Flexbox is generally used for small-scale layouts, whereas Grid is used for larger stuff.

Flexbox has 2 axes. The main axes and the cross axes.

The main axis is defined by the flex-direction property.

The cross axis will automatically run perpendicular to the main axis.

Image Source

Flexbox Main Axis

The main axis is defined by flex-direction.

Flex-direction has 4 possible values:

  • Row
  • Row-reverse
  • Column
  • Column-reverse

In the screenshot below,

display:flex makes container-1 a flex item

flex:1 – for each of the boxes, makes them evenly distributed in terms of their width. As all the flex items are given a value of 1, they are all the same size.

If you were to change the flex value for .box-1 to 4, then box-1 would take up four-sixths (4/6) of the page:

Change the order of Flex Items

With flexbox you can change the order of the flex-items, (the boxes) without changing the HTML.

To do this use the “order” property.

The code below will put box-1 in the second position, left to right.

Flex-direction: Column

By giving the container the flex-direction property, with a value of “column”, the boxes / flex items will stack on top of each other

Justify-Content

You can use the “justify-content” property to align the boxes within the flex container.

justify-content: flex-end; will push all the flex items to the right

Justify-content:center; will place the boxes in the centre of the container

Justify-content:space-between;

Aligns the content spaced evenly across the entire width of the container, with margins in between:

Space-around will add some “space around” the items, so that they have margins in between the items and also to the sides of the left-most and right-most items:

Flex Grow

If after the dimensions of the flex-items have been set, they leave room or space, you can use the “flex-grow” property.

If you give each flex item a flex grow value of 1, then the items will take up an equal amount of the remaining space.

It could be 1, or 100, it won’t make a difference if all the items have the same value.

Below, flex item “one”, is the only flex item with a “flex grow” property, and it therefore takes up all the space that was left over from left to right by the 3 boxes.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s