SmartCodingTips

CSS Flexbox Basics

Flexbox (Flexible Box Layout) is a powerful layout model in CSS that allows items to align, distribute, and adapt within a container, even when their sizes are unknown or dynamic.

1. Creating a Flex Container

To enable Flexbox, set the container’s display property to flex:


.flex-container {
    display: flex;
}
            

2. Flex Direction

Defines the main axis direction (row by default):


.flex-container {
    flex-direction: row;         /* horizontal (default) */
    flex-direction: column;      /* vertical */
}
            

3. Justify Content

Aligns items along the main axis (horizontal in row):


.flex-container {
    justify-content: flex-start;    /* default */
    justify-content: center;
    justify-content: space-between;
    justify-content: space-around;
    justify-content: space-evenly;
}
            

4. Align Items

Aligns items along the cross axis (vertical by default):


.flex-container {
    align-items: stretch;      /* default */
    align-items: center;
    align-items: flex-start;
    align-items: flex-end;
    align-items: baseline;
}
            

5. Flex Wrap

Controls whether items wrap to the next line if necessary:


.flex-container {
    flex-wrap: nowrap;     /* default */
    flex-wrap: wrap;
    flex-wrap: wrap-reverse;
}
            

6. Gap Between Items

Use gap to control spacing between items:


.flex-container {
    display: flex;
    gap: 20px;
}
            

7. Responsive Flex Layout

Flexbox makes it easier to build layouts that adapt to screen size:


@media (min-width: 768px) {
    .flex-container {
        flex-direction: row;
    }
}

@media (max-width: 767px) {
    .flex-container {
        flex-direction: column;
    }
}
            

Conclusion

Flexbox provides an efficient way to layout, align, and distribute space among items in a container β€” especially when the size of the items is unknown or dynamic. It’s a core tool for modern responsive web design.