June 3, 2024
Introduction to Flexbox
The Flexbox layout model is a powerful tool for creating flexible and responsive layouts in CSS. Flexbox makes it easy to align and distribute space among items in a container, even when their size is unknown or dynamic.
Flex Container and Flex Items
A Flexbox layout consists of a flex container and its flex items. The flex container is the parent element, and the flex items are its children. To create a flex container, you use the display: flex;
property on the parent element.
Example:
.container {
display: flex;
}
Flex Properties
Flexbox provides several properties to control the layout and behavior of flex items:
.container {
flex-direction: row; /* row, row-reverse, column, column-reverse */
}
.container {
flex-wrap: nowrap; /* nowrap, wrap, wrap-reverse */
}
.container {
justify-content: flex-start; /* flex-start, flex-end, center, space-between, space-around, space-evenly */
}
.container {
align-items: stretch; /* stretch, flex-start, flex-end, center, baseline */
}
.container {
align-content: stretch; /* stretch, flex-start, flex-end, center, space-between, space-around */
}
Advanced Flexbox Techniques
Flexbox also provides properties for individual flex items:
.item {
order: 1;
}
.item {
flex-grow: 1;
}
.item {
flex-shrink: 1;
}
.item {
flex-basis: 100px;
}
.item {
align-self: auto; /* auto, flex-start, flex-end, center, baseline, stretch */
}
Exercise: Building a Responsive Flexbox Layout
Let's create a responsive layout using Flexbox properties.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Responsive Flexbox Layout</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="container">
<div class="item">Item 1</div>
<div class="item">Item 2</div>
<div class="item">Item 3</div>
<div class="item">Item 4</div>
<div class="item">Item 5</div>
</div>
</body>
</html>
body {
margin: 0;
font-family: Arial, sans-serif;
}
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-around;
align-items: center;
min-height: 100vh;
padding: 20px;
background-color: #f4f4f4;
}
.item {
background-color: #333;
color: white;
padding: 20px;
margin: 10px;
flex: 1 1 200px; /* flex-grow, flex-shrink, flex-basis */
text-align: center;
}
Open the HTML file in a browser to see your responsive Flexbox layout. Experiment with different Flexbox properties to see how they affect the layout and behavior of your items.
Coming Up Next
In Chapter 8, we'll explore the CSS Grid layout, another powerful tool for creating complex and responsive web layouts.
Please Sign In to post a comment.