This tutorial aims to provide a deep understanding of CSS Flexbox, a one-dimensional layout model that offers space distribution between items in an interface and powerful alignment capabilities. We will explore each Flexbox property in detail, focusing on how they influence the layout of flex items.
What you will learn:
- Fundamentals of Flexbox
- Detailed understanding of Flexbox properties
- Practical examples
Prerequisites:
- Basic knowledge of HTML
- Basic knowledge of CSS
Flexbox is a layout model that allows you to layout and align items in a container easily. The main idea behind the flex layout is to give the container the ability to alter its items' width, height, and order to best fill the available space.
The core properties in Flexbox include: display
, flex-direction
, flex-wrap
, justify-content
, align-items
, align-content
, flex-grow
, flex-shrink
, and flex-basis
.
.container {
display: flex;
}
Here, display: flex
makes .container
become a flex container, and its children become flex items.
.container {
display: flex;
flex-direction: row;
}
flex-direction: row
determines the direction of the main axis. The default value is row
, which means the items are laid out in the same direction as the text.
.container {
display: flex;
justify-content: center;
}
justify-content: center
aligns items along the horizontal line in the center of the container.
In this tutorial, we've learned the fundamentals of Flexbox and explored its core properties. Our next step is to practice using these properties to build more complex layouts.
Exercise 1: Create a flex container and place three items in it. Use the justify-content
property to distribute the space between the items.
Solution:
.container {
display: flex;
justify-content: space-between;
}
This will distribute the space evenly between the flex items.
Exercise 2: Now, try to align the items vertically in the center of the container.
Solution:
.container {
display: flex;
align-items: center;
}
align-items: center
will align the flex items vertically in the middle.
For further practice, try to build a simple webpage layout using Flexbox.
Remember, the key to mastering Flexbox is through practice and experimentation. Happy coding!