我正在try 调整一个img的大小与其本身的百分比.例如,我只想通过将图像大小调整为50%来将其缩小一半.但是应用width: 50%;
会将图像大小调整为容器元素(父元素,例如,可能是<body>
)的50%.
问题是,我可以在不使用javascript或服务器端的情况下调整图像的大小吗?(我没有图像大小的直接信息)
我很确定你做不到这一点,但我只是想看看是否有智能CSS唯一的解决方案.谢谢
我正在try 调整一个img的大小与其本身的百分比.例如,我只想通过将图像大小调整为50%来将其缩小一半.但是应用width: 50%;
会将图像大小调整为容器元素(父元素,例如,可能是<body>
)的50%.
问题是,我可以在不使用javascript或服务器端的情况下调整图像的大小吗?(我没有图像大小的直接信息)
我很确定你做不到这一点,但我只是想看看是否有智能CSS唯一的解决方案.谢谢
我有两种方法.
这种方法只调整图像的视觉尺寸,而不是DOM中的实际尺寸,调整后的视觉状态集中在原始尺寸的中间.
html:个
<img class="fake" src="example.png" />
css:个个
img {
-webkit-transform: scale(0.5); /* Saf3.1+, Chrome */
-moz-transform: scale(0.5); /* FF3.5+ */
-ms-transform: scale(0.5); /* IE9 */
-o-transform: scale(0.5); /* Opera 10.5+ */
transform: scale(0.5);
/* IE6–IE9 */
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9999619230641713, M12=-0.008726535498373935, M21=0.008726535498373935, M22=0.9999619230641713,SizingMethod='auto expand');
}
101个浏览器的统计数据显示,css
个浏览器中有css
个是内联的.
html:个
<div id="wrap">
<img class="fake" src="example.png" />
<div id="img_wrap">
<img class="normal" src="example.png" />
</div>
</div>
css:个个
#wrap {
overflow: hidden;
position: relative;
float: left;
}
#wrap img.fake {
float: left;
visibility: hidden;
width: auto;
}
#img_wrap {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
#img_wrap img.normal {
width: 50%;
}
Note: img.normal
and img.fake
is the same image.
Browser support note: This method will work in all browsers, because all browsers support css
properties used in method.
#wrap
和#wrap img.fake
有流量#wrap
具有overflow: hidden
,使得其尺寸与内部图像(img.fake
)相同img.fake
是#wrap
内唯一没有absolute
定位的元素,因此它不会中断第二步#img_wrap
在#wrap
内具有absolute
个定位,并且在尺寸上延伸到整个元件(#wrap
)#img_wrap
与图像的尺寸相同.width: 50%
设置为img.normal
,其大小为#img_wrap
的50%
,因此是原始图像大小的50%
.