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: flax 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.
CSS Flexbox – Interview Questions
Q 1: What is Flexbox?
Ans: A one-dimensional layout model.
Q 2: Main axis and cross axis?
Ans: Direction of content flow and perpendicular axis.
Q 3: What is justify-content?
Ans: Aligns items on main axis.
Q 4: What is align-items?
Ans: Aligns items on cross axis.
Q 5: When to use Flexbox?
Ans: Aligning items in a row or column.
CSS Flexbox – Objective Questions (MCQs)
Q1. Which property defines a flex container?
Q2. Which property controls the direction of flex items?
Q3. Which property aligns items horizontally in Flexbox?
Q4. Which property allows items to wrap onto multiple lines?
Q5. Which property controls how much an item grows?