Module 3: Advanced CSS Techniques
Day 12: Flexbox - Basics and Practical Use
Introduction to Flexbox
Flexbox, or the Flexible Box Layout, is a layout model designed to help you distribute space along a container's main axis and align items within a container. It is great for creating responsive layouts.
Basic Concepts
The primary concepts in Flexbox are the flex container and the flex items. The container is set to use Flexbox layout, and the items inside it are the flex items.
.container {
display: flex;
}
.item {
flex: 1;
}
Container Properties
Here are some important properties for the flex container:
/* Establishes the flex container */
.container {
display: flex;
/* Defines the main axis */
flex-direction: row; /* row, row-reverse, column, column-reverse */
/* Wrap items if necessary */
flex-wrap: nowrap; /* nowrap, wrap, wrap-reverse */
/* Align items along the main axis */
justify-content: flex-start; /* flex-start, flex-end, center, space-between, space-around */
/* Align items along the cross axis */
align-items: stretch; /* flex-start, flex-end, center, baseline, stretch */
/* Align content if there are multiple lines */
align-content: stretch; /* flex-start, flex-end, center, space-between, space-around, stretch */
}
Item Properties
Here are some important properties for the flex items:
.item {
/* Define the grow factor */
flex-grow: 1; /* Default is 0 */
/* Define the shrink factor */
flex-shrink: 1; /* Default is 1 */
/* Define the basis for the item */
flex-basis: auto; /* length, percentage, or auto */
/* A shorthand for flex-grow, flex-shrink, and flex-basis */
flex: 1 1 auto;
/* Override the container's align-items */
align-self: auto; /* auto, flex-start, flex-end, center, baseline, stretch */
}
Practical Example
Let's see a practical example of using Flexbox to create a simple layout:
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
</div>
.container {
display: flex;
justify-content: space-between;
align-items: center;
height: 100vh;
}
.item {
background-color: #0056b3;
color: white;
padding: 20px;
text-align: center;
border-radius: 8px;
}
Example Output:
Item 1
Item 2
Item 3