Home > Net >  Auto resize image depending on screen size (html and css)
Auto resize image depending on screen size (html and css)

Time:08-05

I have a web page written in html and css. Let's suppose my html is composed of just some simple , something like:

<!doctype html>
<head>
     <title>testpage</title>
     <link rel = "stylesheet" href="style.css">
</head>

<body>
  <div id="header">
    header
  </div>

<div id="central_body">
     <div >
          <img id = "image_to_resize" src= "images/image_to_resize.jpg" alt = "">
     </div>
     <div class = "nav">
          nav
     </div>
</div>

<div id="page_footer">
     footer
</div>
</body>

As you can see, there is a div that contains an image. The image can be bigger than the screen. I would like to fit all the content to the screen size to make no scroll bars appear; when fitting the content I would like to rescale the image but keeping its original aspect ratio. I want to keep the img tag in the html code. How could I do? I can use html, css and javascript.

CodePudding user response:

you can use this css property :

.image_area img{
        max-width: 100%;
        max-height: 100%;
        display: block; /* remove extra space below image */
    }

CodePudding user response:

You should set the view port to control the page dimensions and scaling.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

and use percentages % for your div and image width. Set width:100% instead of px

if you want the image container to take up the entire viewport, set the div central_body height: 100vh;

  • Related