CSS

Flexbox Introduction

Regular div container:

A
B
C

Flex Containers

On the container: display: flex or display: inline-flex

Default properties on the container:

Default properties of the flex items:

A
B
C

Flex Items

Easiest way to make the flex items stretches evenly: flex: 1. Apply it on each item.

A
B
C

Complex nesting multiple box

With just those simple declarations, we can create a complex nesting multiple flexbox.

CSS Flexbox

Navigation

A
B
C

/* style.css */

.css-container,
.css-flex-container {
padding: 3px;
border: 3px solid rosybrown;
margin: 20px;
}

.css-flex-container {
display: flex;
}

.css-container div,
.css-flex-container div {
padding: 5px;
border: 3px solid cadetblue;
margin: 5px;
}

.css-flex-container div {
flex: 1;
}

Note

Style the navigation box with flex: 0;
Olivia writes:
FOX FOX FOX FOX, TO, JKUYG

Growing and shrinking

flex is actually a shorthand for flex-grow, flex-shrink, and flex-basis.
The standard value is flex: 0 1 0%.
When declared only with 1 value, it's referring to the flex-grow:
flex: 1
Meaning: grow each child box equally and it is actually flex: 1 1 0%.


Predefined flex shorthand values


Axis

There are 2 axis in the flexbox system: main axis (row) and cross axis (column), and each axis can have 2 directions: regular and reverse.

Note on height of a vertical flexbox

For vertical flexbox, pay attention to the height and flex declaration. When working with horizontal flexbox, shorthand flex: 1 in items is enough to make a smooth flexbox. This code will collapse empty item box in vertical flexbox because it sets the flex-basis at 0, which means it will ignore the predefined height. If the container doesn't have defined height either, and all the item boxes are empty, the container will collapse. This doesn't happen in horizontal box, just in vertical box, because a box by standard stretches horizontally to available space, the whole width, while it stretches vertically only onto the extend of content or predefined height.

So, pay attention to:


flex-wrap: wrap

By default, items will be shrinking when there's no enough horizontal space in the container. If we want the items size to be respected and goes to the next line, use flex-wrap: wrap. Below is an example. Shrink and stretch the window horizontally to see the effect.

The default value is flex-wrap: nowrap btw, in which items will be shrinking instead. The problem is, overflow can happen if items are not able to shrink or can't shrink small enough to fit.

A
B
C
By default, items will be shrinking
when there's no enough horizontal space
Flex-wrap:
wrap

Exercise box

A
B
C