CSS Flexbox (short for Flexible Box Layout) is a CSS layout model designed to distribute and align items within a container efficiently, even when their sizes are dynamic or unknown. It works in a single dimension (either a row or a column) and is particularly useful for creating responsive designs.
How Flexbox Works
1. Flex Container: A parent element with display: flex
or display: inline-flex
. This enables the flexbox behavior for its child elements.
2. Flex Items: The child elements inside the flex container. These are automatically arranged and aligned based on the container’s properties.
Example:
HTML:
<div class="flex-container">
<div class="flex-item">1</div>
<div class="flex-item">2</div>
<div class="flex-item">3</div>
</div>
CSS:
.flex-container {
display: flex; /* Enables Flexbox layout */
justify-content: space-around; /* Distributes items horizontally with equal space around them */
align-items: center; /* Aligns items vertically to the center */
height: 200px; /* Example height to visualize alignment */
background-color: lightgray;
}
.flex-item {
background-color: coral;
padding: 20px;
text-align: center;
color: white;
border-radius: 5px;
}
Result: This creates a horizontally aligned layout where the items are evenly spaced (space-around
) with vertical centering (align-items: center
).
Example: Responsive Navigation Bar
HTML:
<nav class="flex-container">
<div class="flex-item">Home</div>
<div class="flex-item">About</div>
<div class="flex-item">Services</div>
<div class="flex-item">Contact</div>
</nav>
CSS:
.flex-container {
display: flex;
justify-content: space-between; /* Distributes items with space between them */
align-items: center;
background-color: navy;
padding: 10px;
}
.flex-item {
color: white;
padding: 10px 20px;
text-decoration: none;
font-size: 18px;
}
Result:
This creates a responsive navigation bar where items are spaced evenly and aligned in the center.
Flexbox simplifies layout creation, making it an essential tool for modern web design.