Family Magazine

CSS Flexbox for Beginners [2022]

By Geoff Griffiths @mmatraining1980

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.

CSS Flexbox for Beginners [2022]

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.

CSS Flexbox for Beginners [2022]

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
CSS Flexbox for Beginners [2022]

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.

CSS Flexbox for Beginners [2022]

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:

CSS Flexbox for Beginners [2022]

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.

CSS Flexbox for Beginners [2022]

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

CSS Flexbox for Beginners [2022]

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

CSS Flexbox for Beginners [2022]

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

CSS Flexbox for Beginners [2022]

Justify-content:space-between;

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

CSS Flexbox for Beginners [2022]

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:

CSS Flexbox for Beginners [2022]

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.

CSS Flexbox for Beginners [2022]

Back to Featured Articles on Logo Paperblog