Open In App

How to align items at the center of the container using CSS ?

Last Updated : 18 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Centering items in a container using CSS involves aligning elements horizontally and vertically within a parent element. This can be done using different CSS properties and techniques, ensuring that the content appears visually centered and balanced within its container.

Here are some common approaches

Method 1: Centering with text-align, display, and vertical-align Properties

The text-align property specifies the horizontal alignment of text in an element, while the display and vertical-align properties help vertically center the item within the container.

Syntax:

.container {
text-align: center;
display: table-cell;
vertical-align: middle;
}

Example : In this example, centers “Centered Item” vertically and horizontally within .container using text-align: center;, display: table-cell;, and vertical-align: middle;, with a 200px square border.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Centering with Text-Align, Display, and Vertical-Align</title>
    <style>
        .container {
            width: 200px;
            height: 200px;
            border: 1px solid black;
            text-align: center;
            display: table-cell;
            vertical-align: middle;
        }
    </style>
</head>

<body>
    <div class="container">
        Centered Item
    </div>
</body>

</html>

Output:


Center-container-item

Centering items of container by text-align & line-height Property Output

Method 2: Centering with text-align and line-height Properties

The text-align property is used to center the item horizontally, and the line-height property is used to center the item vertically. This approach works best with single-line text.

Syntax:

.container {
text-align: center;
line-height: 200px;
}

Example: In this example centers “Centered Item” within a .container using text-align: center; and line-height: 200px;, contained within a 200px by 200px box with a black border.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Centering with Text-Align and Line-Height</title>
    <style>
        .container {
            width: 200px;
            height: 200px;
            border: 1px solid black;
            text-align: center;
            line-height: 200px;
        }
    </style>
</head>

<body>
    <div class="container">
        Centered Item
    </div>
</body>

</html>

Output:

align-center


Next Article

Similar Reads