CSS Flexbox - Notes By ShariqSP
Understanding CSS Flexbox
CSS Flexbox (Flexible Box Layout) is a layout model designed to provide an efficient way to distribute space and align items in a container, even when their size is dynamic or unknown. Flexbox is great for creating responsive designs. Below are examples to demonstrate its usage.
Example 1: Basic Flex Container
/* Flex container */
.flex-container {
display: flex;
background-color: #f1f1f1;
}
/* Flex items */
.flex-container div {
margin: 10px;
padding: 20px;
background-color: lightblue;
text-align: center;
}
Explanation: The `display: flex` property turns the container into a flex container, aligning the items in a row by default.
Example 2: Aligning Items
.flex-container {
display: flex;
justify-content: center; /* Center items horizontally */
align-items: center; /* Center items vertically */
height: 200px;
background-color: #e3f2fd;
}
.flex-container div {
margin: 10px;
padding: 20px;
background-color: #90caf9;
}
Explanation: The `justify-content` property aligns items horizontally, while `align-items` aligns them vertically within the container.
Example 3: Flex Direction
.flex-container {
display: flex;
flex-direction: column; /* Stack items vertically */
}
.flex-container div {
margin: 10px;
padding: 20px;
background-color: lightgreen;
}
Explanation: The `flex-direction` property changes the layout direction. Setting it to `column` stacks items vertically.
Example 4: Adjusting Item Size
.flex-container {
display: flex;
}
.flex-container div {
flex: 1; /* All items take equal space */
margin: 10px;
padding: 20px;
background-color: #ffcc80;
}
Explanation: The `flex: 1` property makes all items flexible, distributing equal space among them.
Example 5: Wrapping Items
.flex-container {
display: flex;
flex-wrap: wrap; /* Allow items to wrap */
background-color: #c8e6c9;
}
.flex-container div {
flex: 1 1 150px; /* Items shrink and grow as needed */
margin: 10px;
padding: 20px;
background-color: #a5d6a7;
}
Explanation: The `flex-wrap: wrap` property allows items to move to the next line if there isn’t enough space in the container.