Flexbox (Flexible Box Layout) is a CSS layout module that allows you to align and distribute space among items in a container, even when their size is unknown or dynamic.
- Flexbox works in one dimension (row or column) at a time.
- It simplifies tasks like centering, spacing, and ordering elements.
🔹 Basic Flexbox Properties
Container Properties:
display: flex;→ makes an element a flex container.flex-direction: row | column;→ sets main axis.justify-content→ aligns items along main axis (horizontal by default).align-items→ aligns items along cross axis (vertical by default).align-content→ aligns multiple lines of items (for wrapping).
Item Properties:
flex-grow,flex-shrink,flex-basis→ control size and flexibility.align-self→ override cross-axis alignment for a single item.
🔹 Centering Elements Horizontally and Vertically
Example:
.container {
display: flex;
justify-content: center; /* horizontal center */
align-items: center; /* vertical center */
height: 200px;
border: 1px solid #ccc;
}
.item {
width: 100px;
height: 50px;
background-color: #4caf50;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
HTML:
<div class="container">
<div class="item">Centered</div>
</div>
✅ The .item will be perfectly centered inside .container.
🔹 Key Points
- Flexbox is one-dimensional (row or column).
justify-content→ main axis alignment.align-items→ cross axis alignment.- Very useful for responsive layouts and dynamic content.
In short:
Flexbox makes alignment and spacing simple, and centering elements is as easy as usingjustify-content: centerandalign-items: centeron a flex container.