HTML CSS - Flexbox
Using Flexbox for layout and alignment
Flexbox is a powerful layout module in CSS that allows for the design of complex layouts with ease. It provides an efficient way to align and distribute space among items in a container, even when their size is unknown or dynamic. This tutorial covers the basics of using Flexbox for layout and alignment.
Key Points:
- The
display: flex
property enables Flexbox on a container. - Flexbox provides properties for direction, alignment, spacing, and wrapping.
- Flexbox is ideal for responsive designs and dynamic content.
Basic Flexbox Container
To create a Flexbox layout, you need to apply display: flex
to a container element. Here is an example:
.flex-container {
display: flex;
background-color: lightgray;
padding: 10px;
}
.flex-item {
background-color: #4CAF50;
padding: 10px;
margin: 5px;
color: white;
text-align: center;
flex: 1;
}
Flex Direction
The flex-direction
property defines the direction of the flex items. The possible values are row
(default), row-reverse
, column
, and column-reverse
. Here is an example:
.flex-container {
display: flex;
flex-direction: row;
}
.flex-container-column {
display: flex;
flex-direction: column;
}
Justify Content
The justify-content
property aligns flex items along the main axis (horizontal by default). The possible values are flex-start
(default), flex-end
, center
, space-between
, and space-around
. Here is an example:
.flex-container {
display: flex;
justify-content: space-between;
}
Align Items
The align-items
property aligns flex items along the cross axis (vertical by default). The possible values are stretch
(default), flex-start
, flex-end
, center
, and baseline
. Here is an example:
.flex-container {
display: flex;
align-items: center;
}
Flex Wrap
The flex-wrap
property specifies whether flex items should wrap or not. The possible values are nowrap
(default), wrap
, and wrap-reverse
. Here is an example:
.flex-container {
display: flex;
flex-wrap: wrap;
}
Align Self
The align-self
property allows you to override the align-items
property for specific flex items. The possible values are auto
(default), flex-start
, flex-end
, center
, baseline
, and stretch
. Here is an example:
.flex-item {
align-self: center;
}
Summary
In this tutorial, you learned about using Flexbox for layout and alignment in CSS. You explored the basic Flexbox container, flex direction, justify content, align items, flex wrap, and align self properties. Flexbox provides a powerful and flexible way to create responsive and dynamic layouts, making it an essential tool for modern web design.