Welcome to our deep dive into CSS Flexbox! This powerful tool allows us to create flexible and responsive layouts with ease. By the end of this tutorial, you'll be able to build stunning, adaptable designs for the web.
Let's get started!
Flexbox, or Flexible Box Layout, is a CSS module that provides a more intuitive way to design and lay out web content. It allows you to align, distribute, and wrap items with ease, making it perfect for responsive design.
Every Flexbox layout consists of a parent container (the flex container) and its child elements. The container is what gets the display: flex; property, transforming it into a flex container.
.container {
display: flex;
}There are several properties to help you control the behavior of flex containers and their children:
flex-direction: Determines the main axis of the flex container.justify-content: Aligns and distributes items along the main axis.align-items: Aligns items along the cross axis.flex-wrap: Determines whether the items should wrap onto new lines.order: Changes the order of items in the layout.flex-grow, flex-shrink, and flex-basis: Control how items grow, shrink, and start with a specific size.Let's see some examples in action:
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: flex;
flex-wrap: wrap;
}
.item {
flex: 1 0 200px;
margin: 10px;
background-color: #f2f2f2;
}
</style>
</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>
</body>
</html>This example creates a simple four-item grid that wraps onto a new line when necessary. Each item has a fixed minimum width, but can grow or shrink as needed.
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 200px;
}
.item {
width: 200px;
height: 200px;
background-color: #f2f2f2;
}
</style>
</head>
<body>
<div class="container">
<div class="item"></div>
</div>
</body>
</html>This example creates a centered box with a fixed height and width. The content inside is also centered both vertically and horizontally.
Which property controls the main axis of a flex container?
We hope you've enjoyed this introduction to CSS Flexbox! Stay tuned for more advanced examples and tips. Happy coding! 🎉