Home >Web Front-end >CSS Tutorial >How Do I Vertically Center Two Elements Inside a Div?

How Do I Vertically Center Two Elements Inside a Div?

Barbara Streisand
Barbara StreisandOriginal
2024-12-27 17:27:11624browse

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.

The above is the detailed content of How Do I Vertically Center Two Elements Inside a Div?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn