Flexbox (Flexible Box Layout) is a CSS layout model designed to make it easier to align, distribute, and organize elements within a container — even when their sizes are unknown or dynamic.
It’s perfect for 1D layouts (row or column) and helps in creating responsive designs without using floats or positioning tricks.
⚙️ Key Concepts
- Flex container: The parent element with
display: flex. - Flex items: The direct children of the flex container.
- Main axis: The direction of flex items (row or column).
- Cross axis: Perpendicular to the main axis.
🧩 Common Flexbox Properties
display: flex; /* Enables flexbox */
flex-direction: row; /* or column */
justify-content: center; /* Aligns items horizontally */
align-items: center; /* Aligns items vertically */
gap: 10px; /* Adds spacing between items */
💡 Example: Center an Element Horizontally and Vertically
<div class="container">
<div class="box">Centered</div>
</div>
.container {
display: flex;
justify-content: center; /* Centers horizontally */
align-items: center; /* Centers vertically */
height: 100vh; /* Full viewport height */
background: #f3f3f3;
}
.box {
background: teal;
color: white;
padding: 20px 40px;
border-radius: 8px;
}
🧭 Result:
The .box will be perfectly centered both horizontally and vertically inside the .container.
✅ In short:
- Flexbox = best for 1D layouts (row/column).
- Use
justify-contentfor horizontal alignment. - Use
align-itemsfor vertical alignment. - Combine both for perfect centering.