Introduction to CSS Flexbox
What is Flexbox?
Flexbox, or the Flexible Box Layout, is a CSS3 web layout model. It's designed to improve item alignment, directions, and order in the container even when they are with dynamic or even unknown size. The prime characteristic of the Flex container is the ability to modify the width or height of its children to fill the available space in the best possible way on different screen sizes.
How to Use Flexbox
Before you use flexbox, you need to define a container. This is done by setting an element's display property to flex or inline-flex.
.container {
display: flex;
}
This makes the container a flex container and its children become flex items.
Flex Container Properties
A flex container has several properties that can affect the layout of its children:
Flex Direction
The flex-direction property determines the direction of the flex items. By default, they are set to row, which means they are aligned horizontally.
.container {
flex-direction: row; /* default */
}
You can also set it to column if you want the items to be aligned vertically.
.container {
flex-direction: column;
}
Justify Content
The justify-content property aligns the flex items along the horizontal line in the container. You can align the items at the start, end, center or distribute the space between or around them.
.container {
justify-content: center; /* centers items on the line */
}
Align Items
The align-items property is similar to justify content but it works vertically.
.container {
align-items: center; /* centers items vertically */
}
Flex Item Properties
Flex items, or the children of the flex container, also have several properties that can affect their layout within the container.
Flex Grow
The flex-grow property specifies how much a flex item will grow relative to the rest of the flex items.
.item {
flex-grow: 4; /* the item will take up 4 times the space of the other items */
}
Flex Shrink
The flex-shrink property specifies how much a flex item will shrink relative to the rest of the flex items.
.item {
flex-shrink: 2; /* the item will shrink to half the size of the other items */
}
Flex Basis
The flex-basis property specifies the initial size of the item before CSS makes adjustments with flex-shrink or flex-grow.
.item {
flex-basis: 200px; /* the item will start out at 200px wide */
}
Flex
The flex property is a shorthand property for flex-grow, flex-shrink, and flex-basis combined. The second and third parameters (flex-shrink and flex-basis) are optional.
.item {
flex: 1 0 auto;
}
In this tutorial, we only scratched the surface of what you can do with Flexbox. There are many more properties and possibilities you can explore to create flexible and responsive layouts. The more you use Flexbox, the more you'll appreciate its power and flexibility. Remember, practice makes perfect! Happy coding!