How to vertically align an image inside a div using CSS?

In this tutorial, we will learn how to vertically align an image inside a div using CSS properties with the help of examples? By Shahnail Khan Last updated : July 12, 2023

We already know that an image is embedded in a webpage using an img tag in HTML. Just adding images alone won't work, we need to make sure an image is perfectly aligned vertically or horizontally inside a div as well. This tutorial will discuss How to vertically align an image inside a div using CSS?

Vertically align an image inside a div using CSS

The best way to vertically align an image inside a div is by using CSS Flexbox properties. The CSS properties that hold significance here are:

  • display
  • align-items

Set display to "flex" and align-items to "center".

Example

<!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>Tutorial</title>
   </head>
   
   <style>
      .container{
      margin: 1em;
      background-color: #FF7F50;  
      display: flex;
      align-items: center;
      }
      img{
      border: 2px solid black;
      }
   </style>
   
   <body>
      <div class="container">
         <img src="https://static.vecteezy.com/system/resources/thumbnails/000/180/409/small/software_enginner_1-01.png">
      </div>
   </body>
</html>

Output

Output: vertically align an image inside a div

We have created a container class. In container class, we have added an image. By using CSS flexbox properties, an image is aligned vertically inside a div.

CSS Examples »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.