How to Use CSS Flexbox

First, set the display of your container div to be flex.

div {
   display: flex;
} 

When you set a container to display: flex, the browser will automatically format the child elements to all be inline with each other. You can use each child’s flex property to define the width that they take up on the line.

The larger the flex value, the more space it will take up compared to the other elements on the line. For example, if there are 2 elements within the flexbox container (an image and a paragraph), if you set the image’s flex property value to 1 and the paragraph’s to 2, the paragraph will take up 2/3 of the space and the image will take up 1/3 of the space.

Horizontally and vertically align child elements within flexbox container

Let’s say I had a header within my flexbox div and I wanted to center it both horizontally and vertically. I would simply set align-items and justify-content to center:

header {
   align-items: center;
   justify-content: center;
}

The align-items property controls alignment of all items on the cross axis and the justify-content property controls alignment of all items on the main axis.

The align-items and align-self properties control alignment of our flex items on the cross axis, down the columns if flex-direction is row and along the row if flex-direction is column.

Main axis: left to right if flex-direction is row; up and down if flex-direction is column

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