What Is CSS Flexbox?
Flexbox stands for Flexible Box Layout.
It is used to arrange elements in a row or column and control their alignment and spacing.
For example, if we want to display three boxes next to each other, Flexbox makes it easy.
How to Use Flexbox?
To use Flexbox, we need to apply display: flex to a parent element.
HTML:
<div class="container">
<div>Box 1</div>
<div>Box 2</div>
<div>Box 3</div>
</div>
CSS:
.container {
display: flex;
gap: 10px;
}
Here, display: flex arranges the boxes in a row by default, and gap adds space between them.
Important Flexbox Properties
1. display: flex
This property enables Flexbox for the child elements of a container.
.container {
display: flex;
}
2. flex-direction
It controls the direction in which the elements are arranged.
.container {
display: flex;
flex-direction: row;
}
-
rowarranges elements horizontally. -
columnarranges elements vertically. -
row-reversereverses the horizontal order. -
column-reversereverses the vertical order.
3. justify-content
It controls the alignment of elements along the main axis.
.container {
display: flex;
justify-content: center;
}
Some commonly used values are:
-
flex-start— places items at the start. -
center— places items at the center. -
flex-end— places items at the end. -
space-between— places space between items. -
space-around— adds space around items. -
space-evenly— distributes space evenly.
4. align-items
It controls the alignment of items along the cross axis.
.container {
display: flex;
align-items: center;
}
For example, when flex-direction is row, align-items: center vertically centers the items within the container.
5. gap
The gap property adds space between items.
.container {
display: flex;
gap: 20px;
}
This creates a 20px gap between the items.
Where Is Flexbox Used?
Flexbox is commonly used to create:
- Navigation bars
- Buttons arranged in a row
- Card layouts
- Centered content
- Headers and footers
It helps us organize webpage elements without manually adjusting their positions.
Top comments (0)