Flexbox is a modern CSS layout method that makes it easy to create flexible, responsive layouts. It's become the standard way to build layouts on the web.
What is Flexbox?
Flexbox (Flexible Box Layout) is a one-dimensional layout method for arranging items in rows or columns. It automatically handles spacing, alignment, and distribution of space.
Creating a Flex Container
Apply display: flex to make an element a flex container:
.container {
display: flex;
/* Children become flex items */
}
Aligns items along the main axis (horizontal if row, vertical if column):
justify-content: flex-start; /* Items at start (default) */
justify-content: flex-end; /* Items at end */
justify-content: center; /* Items centered */
justify-content: space-between; /* Space between items */
justify-content: space-around; /* Space around items */
justify-content: space-evenly; /* Equal space everywhere */
justify-content: center
Item
Item
Item
justify-content: space-between
Item
Item
Item
align-items
Aligns items along the cross axis (vertical if row, horizontal if column):
align-items: stretch; /* Items fill container (default) */
align-items: flex-start; /* Items at top */
align-items: flex-end; /* Items at bottom */
align-items: center; /* Items centered vertically */
align-items: baseline; /* Items aligned to text baseline */
align-items: center (vertically centered)
Item 1
Item 2
Item 3
flex-wrap
Control whether items wrap to multiple lines:
flex-wrap: nowrap; /* Don't wrap (default) */
flex-wrap: wrap; /* Wrap to new lines */
flex-wrap: wrap-reverse; /* Wrap in reverse */
gap
Space between flex items:
gap: 10px; /* 10px gap between items */
gap: 10px 20px; /* 10px vertical, 20px horizontal */
Flex Item Properties
flex
Controls how much space an item takes. Shorthand for flex-grow, flex-shrink, flex-basis:
flex: 1; /* Grow equally with other flex: 1 items */
flex: 2; /* Take twice as much space as flex: 1 items */
flex: 0 1 200px; /* Don't grow, can shrink, 200px base size */
Different flex values
flex: 1
flex: 2 (2x larger)
flex: 1
align-self
Override container's align-items for a specific item: