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.
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