- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Horizontal and Vertical Center Alignment with Flexbox in CSS3
For horizontal and vertical center alignment with Flexbox, use the align-items property in CSS3. Set the align-items property to center. To center align an image horizontally, use the justify-content property and set it to center.
Center Alignment With Flexbox
The following is the code for horizontal and vertical center alignment with flexbox. The justify-content and align-items properties are set to center −
.h-container { display: flex; width: 300px; height: 300px; background-color: lightblue; justify-content: center; align-items: center; border: 2px solid black; }
Example
Let us see the example −
<!DOCTYPE html> <html> <head> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .h-container { display: flex; width: 300px; height: 300px; background-color: lightblue; justify-content: center; align-items: center; border: 2px solid black; } .h-1 { font-size: 30px; width: 150px; height: 150px; background-color: red; color: white; border: 2px solid rgb(58, 2, 83); } </style> </head> <body> <h2>Horizontal and vertical center alignment using flexbox</h2> <div class="h-container"> <div class="h-1">Centered Div</div> </div> </body> </html>
Center an Image Horizontally
To center an image, we will use the display property in CSS and set it to flex. The horizontal position is set using the justify-content property with value center −
div { display: flex; justify-content: center; }
Example
Let us see an example −
<!DOCTYPE html> <html> <head> <style> div { display: flex; justify-content: center; } </style> </head> <body> <h1>Centering an Image Horizontally</h1> <div> <img src="https://www.tutorialspoint.com/jsf/images/jsf-mini-logo.jpg" /> </div> </body> </html>
Center an Image Vertically
Let us now see how to center an image using the display property in CSS and set it to flex. The vertical position is set using the align-items property with value center −
div { display: flex; align-items: center; }
Example
Let us see an example −
<!DOCTYPE html> <html> <head> <style> div { display: flex; align-items: center; } </style> </head> <body> <h1>Centering an Image Vertically</h1> <div> <img src="https://www.tutorialspoint.com/jsf/images/jsf-mini-logo.jpg" /> </div> </body> </html>