Chapter 6: CSS Flexbox
6.1 Introduction to CSS Flexbox
The CSS Flexbox Layout Module is a powerful tool for creating flexible and responsive layouts. It allows you to align and distribute space among items in a container, even if their sizes are dynamic or unknown.
6.2 Key Properties of Flexbox
- display: Sets an element as a flex container. Use
display: flex;
. - flex-direction: Defines the main axis (row or column).
- justify-content: Aligns items along the main axis.
- align-items: Aligns items along the cross-axis.
- flex-wrap: Determines whether items should wrap onto multiple lines.
6.3 Example: Basic Flexbox Layout
Here’s a simple example of a flex container with three items:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: flex;
flex-direction: row;
justify-content: space-around;
align-items: center;
height: 200px;
background-color: #f8f9fa;
}
.item {
width: 100px;
height: 100px;
background-color: #007bff;
color: white;
text-align: center;
line-height: 100px;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
</div>
</body>
</html>
6.4 Explanation of the Code
In the example above:
display: flex;
makes the container a flexbox.flex-direction: row;
places items in a horizontal line.justify-content: space-around;
distributes items with space around them.align-items: center;
centers items vertically within the container.
6.5 Practical Example: Responsive Navigation Bar
Flexbox can also be used to create a responsive navigation bar:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
background-color: #333;
padding: 10px;
color: white;
}
.navbar a {
color: white;
text-decoration: none;
padding: 0 15px;
}
</style>
</head>
<body>
<div class="navbar">
<div>Logo</div>
<div>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Contact</a>
</div>
</div>
</body>
</html>
6.6 Summary
In this chapter, you learned about the CSS Flexbox layout and its key properties like justify-content
, align-items
, and flex-wrap
. Flexbox simplifies creating responsive layouts and aligning elements. In the next chapter, we’ll explore CSS Grid for building more advanced layouts.
0 Comments