ADVERTISEMENT
ADVERTISEMENT

How to vertically align an image inside a div?

Learn how to how to vertically align an image inside a div using CSS properties?
Submitted by Shahnail Khan, on March 31, 2022

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?

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 Tutorial & Examples »


ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.