CSS Centering Elements
CSS offers several centering methods, and the right one depends on the type of element. Elements can be centered horizontally, vertically, or in both directions.
Example
Flexbox centers this <div> element.
Prompt
Center a div element both horizontally and vertically inside a container using flexbox. The container should have a fixed height (e.g. 300px) and a border. The centered element should display "I am vertically and horizontally centered." Use justify-content: center and align-items: center.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Center with Flexbox</title>
<style>
.center {
display: flex;
justify-content: center;
align-items: center;
height: 300px;
border: 3px solid green;
}
</style>
</head>
<body>
<h2>Center with Flexbox</h2>
<div class="center">
<p>I am vertically and horizontally centered.</p>
</div>
</body>
</html>
Horizontal Alignment
Block elements can be centered with margin: auto, and text inside elements with text-align: center. For left or right alignment, there are float and position.
Vertical Alignment
Modern layout techniques handle vertical centering in several ways: align-items: center in flexbox, place-items: center in grid, and, when an element's dimensions are unknown, position combined with transform.
Tip: To center content in both directions, flexbox is the recommended and most modern choice.