CSS Align
Centering elements is a common requirement in web design. There are several ways to achieve this in CSS, depending on the context.
Center a Block Element
To horizontally center a block-level element (like a <div>), you can set its width and then set the left and right margins to auto.
Example
css
.center-div {
width: 50%;
margin: auto;
border: 3px solid green;
}Center Text
To center the text inside an element, use text-align: center;.
Example
css
.center-text {
text-align: center;
}Center with Flexbox
The modern and most powerful way to center elements is with Flexbox. To center an item both horizontally and vertically, you can apply display: flex;, justify-content: center;, and align-items: center; to the parent container.
Example
css
.flex-container {
display: flex;
justify-content: center; /* Horizontal center */
align-items: center; /* Vertical center */
height: 200px;
}Test Yourself with an Exercise
To horizontally center a block element, you can set `margin: auto;` but what other property must be set?