Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Fit an image in the absolute center of a div and keep the aspect ratio

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 173
    Comment on it

    Hello readers, this is a small blog on auto resize of an image by keeping its aspect ratio and display image horizontally and vertically in the center of the div.

    Here is very simple and easy method to solve this problem of displaying image in the absolute center.

     

    1.  First, make an HTML file index.html and copy the below code in that file  
     

     <!DOCTYPE html>
     <head>
    
     <title>
     Auto Resize an Image
     </title>
    
     <link rel="stylesheet" type="text/css" href="style.css">
    
     </head>
     <body>
     
     <div id="wrapper">
     <img src="img1.jpeg" >
     </div>
     
     </body>
     </html>

     


     2. Now make a CSS style.css file and copy the below-written code in that file.

     

    #wrapper {
      display:table-cell;
      vertical-align:middle;
      text-align:center;
      height:500px;
      width:500px;
      border: 5px solid blue;
    }
    
    #wrapper img
    {
        max-width:100%;
        max-height:100%;
        width:auto;
        height:auto;
    }

     

    Comment: Here we have a div having a class wrapper which I gave CSS {display:table-cell; vertical-align:middle;text-align:center;}, now wrapper div will behave like cell of table and image inside wrapper will display in center vertically and horizontally.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: