CSS alignment properties are used to control the positioning of elements within their containers and to align text or other content within elements. Depending on the context and the type of element, different properties and techniques are used for alignment. Here are some of the most commonly used CSS properties for alignment:
Text Alignment
The text-align
property is used to specify the horizontal alignment of text within an element.
Syntax:
/* Text alignment within an element */
.container {
text-align: left; /* Align text to the left */
text-align: right; /* Align text to the right */
text-align: center; /* Center align text */
text-align: justify; /* Justify text */
}
Vertical Alignment
The vertical-align
property is used to align inline or table-cell elements vertically.
Syntax:
/* Vertical alignment within inline or table-cell elements */
.element {
vertical-align: baseline; /* Default, aligns with the baseline of the parent */
vertical-align: top; /* Aligns with the top of the tallest element */
vertical-align: middle; /* Centers the element vertically */
vertical-align: bottom; /* Aligns with the bottom of the lowest element */
}
Flexbox Alignment
The Flexbox layout model provides powerful alignment capabilities for both the main axis and the cross axis.
Main Axis Alignment
The justify-content
property aligns flex items along the main axis (horizontally for row direction).
Syntax:
/* Main axis alignment within a flex container */
.container {
display: flex;
justify-content: flex-start; /* Align items to the start of the container */
justify-content: flex-end; /* Align items to the end of the container */
justify-content: center; /* Center items within the container */
justify-content: space-between; /* Distribute items with space between */
justify-content: space-around; /* Distribute items with space around */
justify-content: space-evenly; /* Distribute items with equal space around */
}
Cross Axis Alignment
The align-items
property aligns flex items along the cross axis (vertically for row direction).
Syntax:
/* Cross axis alignment within a flex container */
.container {
display: flex;
align-items: flex-start; /* Align items to the start of the cross axis */
align-items: flex-end; /* Align items to the end of the cross axis */
align-items: center; /* Center items along the cross axis */
align-items: baseline; /* Align items along their baselines */
align-items: stretch; /* Stretch items to fill the container (default) */
}