简体   繁体   中英

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

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 class="image_area"> <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.

you can use this css property:

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

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;

Definitely your solution is viewport. The general convention for how to use it is, as listed above:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM