"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to vertically center two elements within a Div?

How to vertically center two elements within a Div?

Posted on 2025-05-02
Browse:304

How Do I Vertically Center Two Elements Inside a Div?

How to Vertically Center Two Elements in a Div

To align two elements vertically within a div, you can use either of the following methods:

1. CSS Flexbox Method

This method involves using the flexbox property to set the flex direction, alignment, and justification of the elements.

CSS Code:

#container {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}

This code will create a flexible container that stacks the elements vertically and centers them both horizontally and vertically.

2. CSS Table and Positioning Method

This method uses the display: table and vertical-align: middle properties to align the elements vertically within the div.

CSS Code:

body {
    display: table;
    position: absolute;
    height: 100%;
    width: 100%;
}

#container {
    display: table-cell;
    vertical-align: middle;
}

This code will make the body element behave like a table, and the #container div will be positioned as a table cell and aligned vertically in the middle.

Recommendation

Flexbox is generally recommended over the table and positioning method due to its modern approach, flexibility, and ease of use.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3