分享CSS中等比例缩放图片

CSS原来只能给图片定义一个固定值,很难做到等比例缩放。因为这里边涉及到运算,而CSS语言中一直都不存在运算的写法。

由于建站中有几块地方需要CSS控制图片等比例缩放,想到今日CSS3高调宣传,感觉CSS3应该能完成此功能。于是上网搜了搜,果然有CSS等比例缩放图片的方法,可惜它并不是CSS3的新特性,但也能用。

img {
  max-width: 600px;
  max-height: 600px;
  scale: expression((this.offsetWidth > this.offsetHeight)?(this.style.width = this.offsetWidth >= 600 ? "600px" : "auto"):(this.style.height = this.offsetHeight >= 600 ? "600px" : "auto")); 
  display:inline;
}

如果你也需要用CSS控制等比例缩放图片,可以把以上代码引用到你的程序中即可。

以上代码中宽与高只是给了一个最大值,可以根据自己的需要修改。第三行就是缩放代码,里边的值也应一并修改。

虽然以上代码还是借用JavaScript完成,但还是感觉挺不错了。

要不然,就得使用一个隐藏图片来是实现

<style type="text/css">
#container {
  width: 100%;
}
.attr {
  background-color: #F5F5F5;
}
.attr img {
  width: 100%;
  height: auto;
}
</style>
<div id='container'>
  <div class='attr'>
    <img src="scale.png" alt="">
  </div>
</div>

也可以用vmin

#container{
  width: 100vmin;
  height: 100vmin;
}

.attr {
  width: 70%;
  height: 50%;
  background-color: black;
}
分享

TITLE: 分享CSS中等比例缩放图片

LINK: https://www.qttc.net/66-css3-width-height-scale.html

NOTE: 原创内容,转载请注明出自琼台博客