Introduction
CSS Flexbox is a powerful layout model that allows web developers to design responsive and efficient layouts. It simplifies aligning elements, distributing space, and creating dynamic structures.
1. What is Flexbox?
Flexbox, or the Flexible Box Layout, is a CSS module designed to layout elements in a one-dimensional space—either row-wise or column-wise.
Key Benefits:
- Simplifies alignment and positioning.
- Efficient space distribution.
- Works well for both small components and entire page layouts.
2. Basic Flexbox Terminology
Flexbox uses two primary elements:
- Flex Container – The parent element that holds flex items.
- Flex Items – The child elements inside the flex container.
Example:
<div class="flex-container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
HTML.flex-container {
display: flex;
background-color: lightgray;
}
.item {
padding: 10px;
background-color: blue;
color: white;
margin: 5px;
}
CSS3. Flex Container Properties
3.1 display: flex;
Turns an element into a flex container.
div {
display: flex;
}
CSS3.2 flex-direction
Defines the direction of items.
div {
flex-direction: row; /* column, row-reverse, column-reverse */
}
CSS3.3 justify-content
Aligns items along the main axis.
div {
justify-content: center; /* flex-start, flex-end, space-between, space-around, space-evenly */
}
CSS3.4 align-items
Aligns items along the cross axis.
div {
align-items: center; /* flex-start, flex-end, stretch, baseline */
}
CSS3.5 align-content
Controls spacing between rows.
div {
align-content: space-between; /* flex-start, flex-end, center, space-around, stretch */
}
CSS4. Flex Item Properties
4.1 flex-grow
Defines how much an item should grow relative to others.
.item {
flex-grow: 1;
}
CSS4.2 flex-shrink
Controls how an item shrinks when space is limited.
.item {
flex-shrink: 2;
}
CSS4.3 flex-basis
Defines the default size before growing or shrinking.
.item {
flex-basis: 100px;
}
CSS4.4 order
Changes the order of flex items.
.item {
order: 2;
}
CSS5. Responsive Design with Flexbox
Using flex-wrap
to make layouts responsive:
.flex-container {
flex-wrap: wrap;
}
CSSExample of a responsive navbar:
.navbar {
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
CSS6. Common Flexbox Layouts
6.1 Centering an Element
.container {
display: flex;
justify-content: center;
align-items: center;
}
CSS6.2 Sidebar Layout
.container {
display: flex;
}
.sidebar {
flex: 1;
}
.main-content {
flex: 3;
}
CSS6.3 Equal Width Columns
.column {
flex: 1;
}
CSSConclusion
Flexbox simplifies layouts and makes responsive design easier. Mastering it will help you build modern, flexible UI structures efficiently.