How can I vertically center a div element for all browsers using CSS?


To vertically center a div element for all browsers using CSS, use the Flexbox. CSS3 provides another layout mode Flexible Box, commonly called as Flexbox. Using this mode, you can easily create layouts for complex applications and web pages. Unlike floats, Flexbox layout gives complete control over the direction, alignment, order, size of the boxes.

The <div> tag is a container for elements in HTML. We can place any type of content inside the div. The elements are first added and then CSS is used to style them. We can now only center the div vertically, but it can be done horizontally.

To vertically centre a div, we will use the flex property, the align-items property. The value is set to center to center the div. In the below example, we have set one of the divs to align center using the align-items property with the value center −

demo2 {
   display: flex;
   align-items: center;
   height: 60%;
} 

The content is then set in the same div demo2 to center align −

<div class="demo2"> <img src="https://www.tutorialspoint.com/archery/images/archery-mini-logo.jpg" alt="Archery Tutorial"> <p>Archery is a bow and arrow game where each player is supposed to shoot arrows from a bow and hit a fixed target.</p> </div>

Example

Let us now see the example to vertically center a div element for all browsers using CSS −

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Center Div Elements</title> </head> <style> body, html { height: 100%; } .demo2 { display: flex; align-items: center; height: 60%; } .demo1, .demo2 { border: 2px solid skyblue; background-color: blue; color: white; } </style> <body> <h1>Archery Tutorial</h1> <div class="demo1"> <img src="https://www.tutorialspoint.com/archery/images/archery-mini-logo.jpg" alt="Archery Tutorial"> <p>Archery is a bow and arrow game where each player is supposed to shoot arrows from a bow and hit a fixed target.</p> </div> <p>Let us now center the div elements: </p> <div class="demo2"> <img src="https://www.tutorialspoint.com/archery/images/archery-mini-logo.jpg" alt="Archery Tutorial"> <p>Archery is a bow and arrow game where each player is supposed to shoot arrows from a bow and hit a fixed target.</p> </div> </body> </html>

Updated on: 21-Nov-2023

781 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements