When making a Web page, there is often a situation where we need to put a picture of an unknown size in a fixed-width container, at which point we need to consider the question:
Only one of the width or height settings for a picture can be scaled like a picture, but the picture may exceed the container size.
Setting a fixed width to a picture can cause a picture to deform.
Some people might simply use JavaScript to solve:
Copy Code code as follows:
<img src= "image-url.png" onload= "if (This.width >) {this.width = 100;} if (This.height >) {this.height = +} "/>
But in this kind of writing in the picture long wide gap is still a picture distortion of the situation, optimized the scaling algorithm code as follows:
Copy Code code as follows:
<!doctype html>
<html lang= "ZH-CN" >
<head>
<meta charset= "UTF-8" >
<title>javascript realize picture scaling </title>
</head>
<body>
<script type= "Text/javascript" >
function Resize (element, MaxWidth, maxheight) {
if (element.width > MaxWidth | | element.height > MaxHeight) {
if (Element.width/element.height > Maxwidth/maxheight) {
element.width = maxwidth;
}else{
element.height = maxheight;
}
}
}
</script>
<img src= "image-url.png" onload= "resize" (this, MB); "/>
</body>
</html>
Without considering IE6, you can use CSS directly, and you don't need to use a low performance CSS expression:
Copy Code code as follows:
<!doctype html>
<meta charset= "UTF-8" >
< title> Pure CSS no expression implementation picture scaling </title>
<style>
. box{
width:300px;
height:300px;
Text-align:center;
border:1px solid #ccc;
}
. Box img{
max-width:100%;
max-height:100%;
Width:auto;
Height:auto;
}
</style>
<body>
<div class= "box" ></div>
</body>