Day 2 - Flexbox

Flexbox is a layout model that allows you to design complex layouts easily and responsively. It usually involves a Parent Container and Child Items.


1. Flex Direction

Controls the direction in which items are laid out.

Code:

/* CSS */
/* Default: Lays out items in a row (Left to Right) */
.row {
    display:  flex;
    flex-direction: row;
}

/* Lays out items in a column (Top to Bottom) */
.column {
    display:  flex;
    flex-direction: column;
}

Output (Row):

1
2
3

Output (Column):

1
2
3

2. Justify Content (Main Axis)

Aligns items horizontally (if direction is row). Useful for spacing.

Code:

/* CSS */
.j-start {
    justify-content: flex-start;
}
/* Default */
.j-center {
    justify-content: center;
}
.j-end {
    justify-content: flex-end;
}
.j-between {
    justify-content: space-between;
}
.j-around {
    justify-content: space-around;
}

Output:

space-between (pushes items to edges):

1
2
3

center:

1
2
3

3. Align Items (Cross Axis)

Aligns items vertically (if direction is row).

Code:

/* CSS */
.a-center {
    align-items:  center;
}
.a-stretch {
    align-items:  stretch;
} /* Default: Stretch to fill height */

Output:

center (vertical middle):

40px
80px
60px

stretch (default):

Auto Height
Auto Height
Auto Height

4. Flex Wrap

Allows items to wrap onto multiple lines if there isn't enough space.

Code:

/* CSS */
.wrap-container {
    display:  flex;
    flex-wrap:  wrap;
    width:  300px;
}

Output:

1
2
3
4
5

5. Practical Example: Navigation Bar

Common pattern: Logo on the left, Links on the right.

Code:

/* CSS */
.navbar {
    display:  flex;
    justify-content: space-between; /* Push apart */
    align-items:  center;
}

Output: