How to align items at the center of the container using CSS ?
An easy and common task for CSS is to align text or images into the center of any container.
Syntax:
.container{ text-align: center; }
Example 1: We use the text-align property of CSS to center the item horizontally followed by the vertical-align and display property to align the item to the center of the container vertically. Below examples illustrate the approach:
HTML
<!DOCTYPE html> < html > < head > < style > .container{ text-align: center; height: 200px; width : 200px; display: table-cell; vertical-align: middle; border: 2px solid green; } </ style > </ head > < body > < div class = "container" > < p >Centered Text</ p > </ div > </ body > </ html > |
Output :

Text is centered in the container
Example 2: Another method is to use the text-align property to center the item horizontally with the line-height property to align the items at the center of the container vertically. Below examples illustrate the approach:
HTML
<!DOCTYPE html> < html > < head > < style > .container2{ width: 200px; line-height: 180px; height: 200px; text-align: center; border: 2px solid green; } </ style > </ head > < body > < div class = "container2" > < p >Centered Text</ p > </ div > </ body > </ html > |
Output:

Text is centered in the container
Please Login to comment...