CSS Flexbox

Master modern layouts with flexible, responsive, and easy-to-control designs.

What is CSS Flexbox?

CSS Flexbox (Flexible Box Layout) is a layout system designed to arrange elements in a row or column easily, even when their size is unknown or dynamic.

  • Align items horizontally and vertically
  • Create responsive layouts easily
  • No floats or complex positioning
  • Perfect for navbars, cards, and UI layouts

Real-Life Example: Like arranging items neatly inside a box that automatically adjusts space.

display: flex

To start using Flexbox, you must first make a container a flex container.

Basic Flex Container


.container {
    display: flex; 
    /* Enables flexbox for this container */
}

                

Once display: flex is applied:

  • Child elements become flex items
  • Items align in a row by default
  • Layout becomes flexible and responsive

flex-direction

flex-direction controls the direction of flex items.

Flex Direction Example


.container {
    display: flex;

    flex-direction: row; 
    /* row → items placed left to right (default) */

    /* flex-direction: column; */
    /* column → items placed top to bottom */
}

                
  • row – horizontal (default)
  • column – vertical
  • row-reverse – reverse horizontal
  • column-reverse – reverse vertical

justify-content

justify-content aligns items along the main axis.

Horizontal Alignment


.container {
    display: flex;

    justify-content: space-between;
    /* space-between → equal space between items */

    /* justify-content: center; */
    /* center → items move to center */
}

                
  • flex-start – start position
  • center – center alignment
  • space-between – equal gaps
  • space-around – space around items

align-items

align-items aligns items along the cross axis (vertical by default).

Vertical Alignment


.container {
    display: flex;
    height: 200px;

    align-items: center;
    /* center → vertically centers items */
}

                
  • stretch – default, fills height
  • center – center vertically
  • flex-start – top
  • flex-end – bottom

flex-wrap

flex-wrap controls whether items wrap to the next line.

Wrapping Items


.container {
    display: flex;
    flex-wrap: wrap;
    /* wrap → items move to next line if space is less */
}

                

Best Practices for Flexbox

  • Use Flexbox for 1D layouts (row or column)
  • Combine with CSS Grid for complex layouts
  • Avoid over-nesting flex containers
  • Always define alignment intentionally

Pro Tip: If you can explain your layout in one direction, Flexbox is the right choice.