Flexbox is a CSS layout model that lets you design responsive and efficient layouts with ease. Here is a structured guide to implementing Flexbox:
1. Define a Flex Container
To use Flexbox, the parent container must have display: flex or display: inline-flex. This turns the container into a flex container, and its children become flex items
.container {
display: flex; /* Enables Flexbox */
}
2. Manage Flex Items
All direct children of the flex container are considered flex items. Those items can be styled by a set of Flexbox properties.
3. Popular Flexbox Properties
Below is the most popular Flexbox properties you'll use:
flex-direction: Defines the order of flex items.
.container {
flex-direction: row; /* column, row-reverse, column-reverse */
}
justify-content: Justifies items according to an axis. Items are aligned along the main axis (horizontal by default).
.container
justify-content: center; /* Options: flex-start, flex-end, space-between, space-around, space-evenly */
}
align-items: Aligns items along the cross axis (vertical by default).
.container {
align-items: stretch; /* Options: flex-start, flex-end, center, baseline */
}
flex-wrap: Determines whether items should wrap to the next line if there's insufficient space.
.container {
flex-wrap: wrap; /* Options: no-wrap, wrap-reverse */
}
4. Flex Item-Specific Properties
Flex items can be individually customized with properties like:
flex-grow: Specifies how much an item will grow relative to others.
.item {
flex-grow: 1; /* Grow equally */
}
flex-shrink: Specifies how much an item will shrink relative to others.
.item {
flex-shrink: 1; /* Shrink equally */
}
flex-basis: Specifies the initial size of an item before growing or shrinking.
.item {
flex-basis: 100px; /* Initial size */
}
align-self: Provides for individual alignment of an item along the cross axis.
.item {
align-self: flex-end; /* Options: auto, flex-start, center */
}
5. Example:
.container {
display: flex;
flex-direction: row; /* Horizontal layout */
justify-content: space-between; /* Spread items evenly */
align-items: center; /* Center items vertically */
flex-wrap: wrap; /* Wrap items if necessary */
}
.item {
flex: 1 1 200px; /* Grow, shrink, and set an initial size */
margin: 10px; /* Add spacing */