CSS Flexbox Layout Tutorial
Flexbox is a modern CSS layout system used to create flexible and responsive layouts.
It allows developers to align, distribute, and control space between elements easily.
Flexbox works using a flex container and flex items inside that container.
Flex Container
A flex container is created using the display flex property.
CSS
Flex Container Example
.container {
display: flex;
}
Flex Items
All direct children inside a flex container become flex items.
HTML
Flex Items Example
<div class="container">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
</div>
Justify Content
The justify-content property aligns items horizontally inside the container.
- flex-start
- flex-end
- center
- space-between
- space-around
CSS
Justify Content Example
.container {
display: flex;
justify-content: center;
}
Align Items
The align-items property aligns items vertically.
CSS
Align Items Example
.container {
display: flex;
align-items: center;
height: 200px;
}
Flex Direction
Flex direction controls the direction of flex items.
- row
- column
- row-reverse
- column-reverse
CSS
Flex Direction Example
.container {
display: flex;
flex-direction: column;
}
Complete Flexbox Example
CSS
Flexbox Layout Example
.container {
display: flex;
justify-content: space-between;
align-items: center;
}
.box {
width: 100px;
height: 100px;
background: lightblue;
}
Best Practices
- Use flexbox for responsive layouts.
- Combine justify-content and align-items for alignment.
- Use flex-direction for vertical layouts.
- Avoid unnecessary nested flex containers.
Conclusion
CSS Flexbox is a powerful layout tool that simplifies alignment and spacing in web design.
By mastering flexbox properties, developers can create responsive and flexible layouts easily.
Codecrown