Flexbox Introduction
Flexbox is a CSS layout mode that makes it easy to arrange elements in a flexible, responsive way. It's ideal for one-dimensional layouts like navigation, toolbars, and single-row/column arrangements. The container distributes space and alignment to children automatically.
Flexbox Concepts
Concept | Description | Example |
|---|---|---|
Flex container | Parent with display: flex | Navigation bar |
Flex items | Direct children of container | Nav links |
Main axis | Primary direction (horizontal) | Left to right |
Cross axis | Perpendicular direction | Top to bottom |
/* Enable flexbox */
.container {
display: flex;
/* Children become flex items */
}
/* Basic flex container */
.navbar {
display: flex;
gap: 20px;
align-items: center;
padding: 15px;
}
.navbar a {
/* Becomes flex item */
padding: 10px 15px;
}
/* Column layout */
.sidebar {
display: flex;
flex-direction: column;
height: 100vh;
}Main Flex Properties
Property | Purpose | Example |
|---|---|---|
display: flex | Enable flexbox | display: flex |
flex-direction | Main axis direction | flex-direction: row |
justify-content | Main axis alignment | justify-content: center |
align-items | Cross axis alignment | align-items: center |
gap | Space between items | gap: 20px |
Common Flex Layouts
/* Horizontal navigation */
nav {
display: flex;
gap: 20px;
padding: 15px;
background: #333;
}
nav a {
color: white;
padding: 10px 15px;
text-decoration: none;
}
/* Vertical sidebar */
.sidebar {
display: flex;
flex-direction: column;
width: 250px;
gap: 10px;
}
/* Centered container */
.hero {
display: flex;
align-items: center;
justify-content: center;
height: 400px;
background: linear-gradient(to right, blue, purple);
color: white;
}
/* Space-between layout */
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 15px;
}