Pure CSS without expression to achieve unknown size picture scaling (support IE7 and above)

Source: Internet
Author: User
Tags expression

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>

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.